Beispiel #1
0
    def test_nested_flatten_with_multiple_values_2(self):
        class CM(ComplexModel):
            i = Integer
            s = String

        class CCM(ComplexModel):
            c = CM.customize(max_occurs=2)
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(CCM, _returns=String)
            def some_call(ccm):
                return repr(ccm)

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 'ccm_i=1&ccm_s=s&ccm_c_i=3&ccm_c_s=cs',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)

        try:
            server.get_in_object(ctx)
        except:
            pass
        else:
            raise Exception("Must fail with: Exception: HttpRpc deserializer "
                        "does not support non-primitives with max_occurs > 1")
Beispiel #2
0
    def test_multiple_return(self):
        class SomeNotSoComplexModel(ComplexModel):
            s = String

        class SomeService(ServiceBase):
            @srpc(_returns=[Integer, String])
            def some_call():
                return 1, 's'

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': '',
            'PATH_INFO': '/some_call',
            'QUERY_STRING': '?s=a',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        try:
            ctx, = server.generate_contexts(initial_ctx)
            server.get_in_object(ctx)
            server.get_out_object(ctx)
            server.get_out_string(ctx)
        except ValueError:
            pass
        else:
            raise Exception("Must fail with: HttpRpc does not support complex "
                "return types.")
Beispiel #3
0
    def test_primitive_only(self):
        class SomeComplexModel(ComplexModel):
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(SomeComplexModel, _returns=SomeComplexModel)
            def some_call(scm):
                return SomeComplexModel(i=5, s='5x')

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': '',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')
        ctx, = server.generate_contexts(initial_ctx)

        server.get_in_object(ctx)
        server.get_out_object(ctx)
        try:
            server.get_out_string(ctx)
        except:
            pass
        else:
            raise Exception("Must fail with: HttpRpc does not support complex "
                "return types.")
Beispiel #4
0
    def test_complex(self):
        class CM(ComplexModel):
            i = Integer
            s = String

        class CCM(ComplexModel):
            c = CM
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(CCM, _returns=CCM)
            def some_call(ccm):
                return CCM(c=ccm.c, i=ccm.i, s=ccm.s)

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)
        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': '',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')
        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)
Beispiel #5
0
def main(argv):
    observer = log.PythonLoggingObserver('twisted')
    log.startLoggingWithObserver(observer.emit, setStdout=False)

    wsgi_application = WsgiApplication(soap_application)

    return run_twisted([(wsgi_application, url)], port)
Beispiel #6
0
    def setup_services(self, applications):
        """Setting up the service that should be run by twisted. This is here
        an rpclib service in the standard WSGI format."""
        if type(applications) not in (list, tuple, dict):
            applications = [applications]

        self.service = rpclib.application.Application(
            applications,
            tns=self.namespace,
            interface=Wsdl11(),
            in_protocol=Soap11(validator='lxml'),
            out_protocol=Soap11())
        self.wsgi_application = WsgiApplication(self.service)
Beispiel #7
0
def wsgi_soap11_application(services,
                            tns='rpclib.simple.soap',
                            validator=None):
    """Wraps `services` argument inside a WsgiApplication that uses Wsdl 1.1 as
    interface document and Soap 1.1 and both input and output protocols.
    """

    application = Application(services,
                              tns,
                              interface=Wsdl11(),
                              in_protocol=Soap11(validator=validator),
                              out_protocol=Soap11())

    return WsgiApplication(application)
Beispiel #8
0
    def test_string_array(self):
        class SomeService(ServiceBase):
            @srpc(String(max_occurs='unbounded'), _returns=Array(String))
            def some_call(s):
                return s

        app = Application([SomeService], 'tns', HttpRpc(), HtmlTable(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 's=1&s=2',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        assert ''.join(ctx.out_string) == '<table class="some_callResponse"><tr><th>string</th></tr><tr><td>1</td></tr><tr><td>2</td></tr></table>'
Beispiel #9
0
    def test_multiple(self):
        class SomeService(ServiceBase):
            @srpc(String(max_occurs='unbounded'), _returns=String)
            def some_call(s):
                return '\n'.join(s)

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 's=1&s=2',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        assert ctx.out_string == ['1\n2']
Beispiel #10
0
    def __call__(self, request):
        django_response = HttpResponse()

        def start_response(status, headers):
            status, reason = status.split(' ', 1)

            django_response.status_code = int(status)
            for header, value in headers:
                django_response[header] = value

        environ = request.META.copy()
        environ['wsgi.input'] = request
        environ['wsgi.multithread'] = False

        response = WsgiApplication.__call__(self, environ, start_response)

        django_response.content = "\n".join(response)

        return django_response
Beispiel #11
0
    def __call__(self, request):
        django_response = HttpResponse()

        def start_response(status, headers):
            status, reason = status.split(' ', 1)

            django_response.status_code = int(status)
            for header, value in headers:
                django_response[header] = value

        environ = request.META.copy()
        environ['wsgi.input'] = request
        environ['wsgi.multithread'] = False

        response = WsgiApplication.__call__(self, environ, start_response)

        django_response.content = "\n".join(response)

        return django_response
    def test_simple(self):
        class SomeService(ServiceBase):
            @srpc(String, _returns=String)
            def some_call(s):
                return s

        app = Application([SomeService], 'tns', HttpRpc(), HtmlMicroFormat(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 's=s',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        assert ctx.in_error is None

        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult">s</div></div>'
    def test_multiple_return(self):
        class SomeNotSoComplexModel(ComplexModel):
            s = String

        class SomeService(ServiceBase):
            @srpc(_returns=[Integer, String])
            def some_call():
                return 1, 's'

        app = Application([SomeService], 'tns', HttpRpc(), HtmlMicroFormat(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': '',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult0">1</div><div class="some_callResult1">s</div></div>'
Beispiel #14
0
    def test_nested_flatten(self):
        class CM(ComplexModel):
            i = Integer
            s = String

        class CCM(ComplexModel):
            c = CM
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(CCM, _returns=String)
            def some_call(ccm):
                return repr(ccm)

        app = Application([SomeService], 'tns', HttpRpc(), HttpRpc(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 'ccm_i=1&ccm_s=s&ccm_c_i=3&ccm_c_s=cs',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)

        server.get_in_object(ctx)
        assert ctx.in_error is None

        server.get_out_object(ctx)
        assert ctx.out_error is None

        server.get_out_string(ctx)

        print ctx.out_string
        assert ctx.out_string == ["CCM(i=1, c=CM(i=3, s='cs'), s='s')"]
Beispiel #15
0
    def setup_services(self, applications):
        """Setting up the service that should be run by twisted. This is here
        an rpclib service in the standard WSGI format."""
        if type(applications) not in (list, tuple, dict):
            applications = [applications]

        # Set the encoding for SOAP data, converting it from unicode to some
        # str encoding. We could instead use the Unicode classes, but Cerebrum
        # doesn't support unicode natively quite yet.
        String.Attributes.encoding = 'latin1'

        # Ignore unencodable characters
        # The following function does the same as String.from_string, except
        # that it supplies 'ignore' as an argument to encode()
        from rpclib.model import nillable_string

        @classmethod
        @nillable_string
        def from_string(cls, value):
            retval = value
            if isinstance(value, unicode):
                if cls.Attributes.encoding is None:
                    raise Exception("You need to define an encoding to "
                                    "convert the incoming unicode values to.")
                else:
                    retval = value.encode(cls.Attributes.encoding, 'ignore')
            return retval

        String.from_string = from_string

        self.service = rpclib.application.Application(
            applications,
            tns=self.namespace,
            interface=Wsdl11(),
            in_protocol=Soap11(validator='lxml'),
            out_protocol=Soap11())
        self.wsgi_application = WsgiApplication(self.service)
Beispiel #16
0
    if "session-id" not in cookie:
        raise UnauthenticatedError()
    session_cookie = cookie["session-id"].value
    session_id = tuple(base64.urlsafe_b64decode(session_cookie).split("\0", 1))
    if not session_id in session_db:
        raise AuthenticationError(session_id[0])
    ctx.udc = session_id[0]     # user name
    

UserService.event_manager.add_listener('method_call', _on_method_call)

if __name__=='__main__':
    from rpclib.util.wsgi_wrapper import run_twisted

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)
    logging.getLogger('twisted').setLevel(logging.DEBUG)

    application = Application([UserService],
        tns='rpclib.examples.authentication',
        interface=Wsdl11(),
        in_protocol=Soap11(validator='lxml'),
        out_protocol=Soap11()
    )

    twisted_apps = [
        (WsgiApplication(application), 'app'),
    ]

    sys.exit(run_twisted(twisted_apps, 7789))
Beispiel #17
0
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('rpclib.protocol.xml')
logger.setLevel(logging.DEBUG)

from rpclib.application import Application
from rpclib.test.interop.server._service import services
from rpclib.protocol.csv import OutCsv
from rpclib.protocol.http import HttpRpc
from rpclib.interface.wsdl import Wsdl11

httprpc_csv_application = Application(
    services, 'rpclib.test.interop.server.httprpc.csv', Wsdl11(), HttpRpc(),
    OutCsv())
from rpclib.server.wsgi import WsgiApplication

if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
        from wsgiref.validate import validator

        wsgi_application = WsgiApplication(httprpc_csv_application)
        server = make_server('0.0.0.0', 9755, validator(wsgi_application))

        logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9755))
        logger.info('WSDL is at: /?wsdl')
        server.serve_forever()

    except ImportError:
        print("Error: example server code requires Python >= 2.5")
# We are going to use the ubiquitious Http protocol as a transport, using a Wsgi-compliant http server.
# This example uses Python’s stock simple wsgi web server. Rpclib has been tested with several other web servers.
# Any WSGI-compliant server should work.

# This is the required import:
if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
    except ImportError:
        print "Error: example server code requires Python >= 2.5"

    # Here, we configure the python logger to show debugging output. We have to specifically enable the debug output from the soap handler.
    # That’s because the xml formatting code is run only when explicitly enabled for performance reasons
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)

    # We glue the service definition, interface document and input and output protocols under the targetNamespace ‘opinionAnalysys.api.analyseOpinion.soap’:
    application = Application([opinionAnalisys_Service],
                              'opinionAnalysys.api.analyseOpinion.soap',
                              interface=Wsdl11(),
                              in_protocol=Soap11(),
                              out_protocol=Soap11())

    server = make_server(
        '127.0.0.1', 7789, WsgiApplication(application)
    )  # We then wrap the rpclib application with its wsgi wrapper:

    print "listening to http://127.0.0.1:7789. wsdl is at: http://localhost:7789/?wsdl"

    server.serve_forever()
Beispiel #19
0
            freebusy = []
            for fb_request in fb_requests:
                calendar_folder = fb_request["folder"]
                if calendar_folder is None:
                    log.warn("no calendar folder found for '%s'" % user_email)
                    fb_response \
                        = ExchangeService._freebusy_lookup_error_response()
                else:
                    fb_response \
                        = ExchangeService._freebusy_response(calendar_folder,
                                                             timezone,
                                                             freebusy_view_options)
                freebusy.append(fb_response)
        else:
            freebusy = None

        if suggestions_view_options is not None:
            suggestions \
                = ExchangeService._suggestions_response(timezone,
                                                        suggestions_view_options)
        else:
            suggestions = None
        
        return (freebusy, suggestions)

EwsApp = Application([ExchangeService], EWS_M_NS,
                     name="ExchangeApplication",
                     interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11())

AsController = WsgiApplication(EwsApp)
Beispiel #20
0
    def test_rpc(self):
        import sqlalchemy
        from sqlalchemy import sql

        class KeyValuePair(TableSerializer, self.DeclarativeBase):
            __tablename__ = 'key_value_store'
            __namespace__ = 'punk'

            key = Column(sqlalchemy.String(100), nullable=False, primary_key=True)
            value = Column(sqlalchemy.String, nullable=False)

        self.metadata.create_all(self.engine)

        import hashlib

        session = self.Session()

        for i in range(1, 10):
            key = str(i)
            m = hashlib.md5()
            m.update(key)
            value = m.hexdigest()

            session.add(KeyValuePair(key=key, value=value))

        session.commit()

        from rpclib.service import ServiceBase
        from rpclib.model.complex import Array
        from rpclib.model.primitive import String

        class Service(ServiceBase):
            @rpc(String(max_occurs='unbounded'),
                    _returns=Array(KeyValuePair),
                    _in_variable_names={
                        'keys': 'key'
                    }
                )
            def get_values(ctx, keys):
                session = self.Session()

                return session.query(KeyValuePair).filter(sql.and_(
                    KeyValuePair.key.in_(keys)
                )).order_by(KeyValuePair.key)

        application = Application([Service],
            interface=Wsdl11(),
            in_protocol=HttpRpc(),
            out_protocol=Soap11(),
            name='Service', tns='tns'
        )
        server = WsgiApplication(application)

        initial_ctx = WsgiMethodContext(server, {
            'REQUEST_METHOD': 'GET',
            'QUERY_STRING': 'key=1&key=2&key=3',
            'PATH_INFO': '/get_values',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        i = 0
        for e in ctx.out_document[0][0][0]:
            i+=1
            key = str(i)
            m = hashlib.md5()
            m.update(key)
            value = m.hexdigest()

            _key = e.find('{%s}key' % KeyValuePair.get_namespace())
            _value = e.find('{%s}value' % KeyValuePair.get_namespace())

            print((_key, _key.text))
            print((_value, _value.text))

            self.assertEquals(_key.text, key)
            self.assertEquals(_value.text, value)
Beispiel #21
0
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('rpclib.protocol.xml')
logger.setLevel(logging.DEBUG)

from rpclib.application import Application
from rpclib.test.interop.server._service import services
from rpclib.protocol.soap import Soap11
from rpclib.protocol.http import HttpRpc
from rpclib.interface.wsdl import Wsdl11

httprpc_soap_application = Application(services,
    'rpclib.test.interop.server.httprpc.soap', Wsdl11(), HttpRpc(), Soap11())

from rpclib.server.wsgi import WsgiApplication

if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
        from wsgiref.validate import validator

        wsgi_application = WsgiApplication(httprpc_soap_application)
        server = make_server('0.0.0.0', 9756, validator(wsgi_application))

        logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9756))
        logger.info('WSDL is at: /?wsdl')
        server.serve_forever()

    except ImportError:
        print("Error: example server code requires Python >= 2.5")
Beispiel #22
0
    except ImportError:
        print("Error: example server code requires Python >= 2.5")

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)

    application = Application([HelloWorldService],
                              'rpclib.examples.events',
                              interface=Wsdl11(),
                              in_protocol=Soap11(),
                              out_protocol=Soap11())

    application.event_manager.add_listener('method_call', _on_method_call)
    application.event_manager.add_listener('method_return_object',
                                           _on_method_return_object)
    application.event_manager.add_listener('method_context_constructed',
                                           _on_method_context_constructed)
    application.event_manager.add_listener('method_context_destroyed',
                                           _on_method_context_destroyed)

    wsgi_wrapper = WsgiApplication(application)
    wsgi_wrapper.event_manager.add_listener('wsgi_call', _on_wsgi_call)
    wsgi_wrapper.event_manager.add_listener('wsgi_return', _on_wsgi_return)

    server = make_server('127.0.0.1', 7789, wsgi_wrapper)

    print("listening to http://127.0.0.1:7789")
    print("wsdl is at: http://localhost:7789/?wsdl")

    server.serve_forever()
    def test_complex(self):
        class CM(ComplexModel):
            i = Integer
            s = String

        class CCM(ComplexModel):
            c = CM
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(CCM, _returns=CCM)
            def some_call(ccm):
                return CCM(c=ccm.c,i=ccm.i, s=ccm.s)

        app = Application([SomeService], 'tns', HttpRpc(), HtmlMicroFormat(), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 'ccm_c_s=abc&ccm_c_i=123&ccm_i=456&ccm_s=def',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        #
        # Here's what this is supposed to return:
        #
        # <div class="some_callResponse">
        #   <div class="some_callResult">
        #     <div class="i">456</div>
        #     <div class="c">
        #       <div class="i">123</div>
        #       <div class="s">abc</div>
        #     </div>
        #     <div class="s">def</div>
        #   </div>
        # </div>
        #

        elt = html.fromstring(''.join(ctx.out_string))
        resp = elt.find_class('some_callResponse')
        assert len(resp) == 1
        res = resp[0].find_class('some_callResult')
        assert len(res) == 1

        i = res[0].findall('div[@class="i"]')
        assert len(i) == 1
        assert i[0].text == '456'

        c = res[0].findall('div[@class="c"]')
        assert len(c) == 1

        c_i = c[0].findall('div[@class="i"]')
        assert len(c_i) == 1
        assert c_i[0].text == '123'

        c_s = c[0].findall('div[@class="s"]')
        assert len(c_s) == 1
        assert c_s[0].text == 'abc'

        s = res[0].findall('div[@class="s"]')
        assert len(s) == 1
        assert s[0].text == 'def'
Beispiel #24
0
            raise Fault("Client.FileName", "File '%s' not found" % file_path)

        document = open(file_path, 'rb').read()

        # the service automatically loads the data from the file.
        # alternatively, The data could be manually loaded into memory
        # and loaded into the Attachment like:
        #   document = Attachment(data=data_from_file)
        return [document]


if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
    except ImportError:
        print("Error: example server code requires Python >= 2.5")

    application = Application([DocumentArchiver],
                              'rpclib.examples.binary',
                              interface=Wsdl11(),
                              in_protocol=HttpRpc(),
                              out_protocol=HttpRpc())

    logging.basicConfig(level=logging.DEBUG)

    server = make_server('127.0.0.1', 7789, WsgiApplication(application))
    print("listening to http://127.0.0.1:7789")
    print("wsdl is at: http://localhost:7789/?wsdl")

    server.serve_forever()
Beispiel #25
0
        for tz in tz_matches:
            time_tz = timezone(tz)
            print(tz, ': ', str(datetime.now(time_tz)))
            string = string + tz + str(datetime.now(time_tz)) + '\n'
        return string


if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
    except ImportError:
        print "Error: server requires Python >= 2.5"

    logging.basicConfig(level=logging.INFO)
    logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)

    application = Application(
        [tz],
        'org.temporary.soap',
        #               interface=Wsdl11(),
        in_protocol=Soap11(),
        out_protocol=Soap11())

    #   port = int(os.environ.get('PORT', 5000))
    port = 8000
    server = make_server('127.0.0.1', port, WsgiApplication(application))

    print "listening to http://127.0.0.1:%s" % port
    print "wsdl is at: http://127.0.0.1:%s/?wsdl" % port

    server.serve_forever()
Beispiel #26
0
    def send_location(clientid):
        print "Asking the RMI Server about ", clientid
        push_property = Pyro4.Proxy("PYRONAME:property.id")
        a = push_property.scanProplist(clientid)
        yield str(a)


if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
    except ImportError:
        print "Error: server requires Python >= 2.5"

    logging.basicConfig(level=logging.INFO)
    logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)

    application = Application([MessageService],
                              'org.temporary.soap',
                              interface=Wsdl11(),
                              in_protocol=Soap11(),
                              out_protocol=Soap11())

    port = int(os.environ.get('PORT', 5007))

    server = make_server('0.0.0.0', port, WsgiApplication(application))

    print "listening to http://0.0.0.0:%s" % port
    print "wsdl is at: http://0.0.0.0:%s/?wsdl" % port

    server.serve_forever()
Beispiel #27
0

class HelloWorldService(ServiceBase):
    @srpc(String, Integer, _returns=Array(String))
    def say_hello(name, times):
        '''Docstrings for service methods appear as documentation in the wsdl.

        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''
        results = []
        for i in range(0, times):
            results.append('Hello, %s' % name)

        return results


if __name__ == '__main__':
    application = Application([HelloWorldService],
                              'rpclib.examples.hello.twisted',
                              interface=Wsdl11(),
                              in_protocol=Soap11(),
                              out_protocol=Soap11())
    wsgi_app = WsgiApplication(application)

    print('listening on 0.0.0.0:7789')
    print('wsdl is at: http://0.0.0.0:7789/app/?wsdl')

    run_twisted(((wsgi_app, "app"), ), 7789)
Beispiel #28
0
    def test_complex_array(self):
        class CM(ComplexModel):
            i = Integer
            s = String

        class CCM(ComplexModel):
            c = CM
            i = Integer
            s = String

        class SomeService(ServiceBase):
            @srpc(CCM, _returns=Array(CCM))
            def some_call(ccm):
                return [ccm] * 5

        app = Application([SomeService], 'tns', HttpRpc(), HtmlTable(field_name_attr='class'), Wsdl11())
        server = WsgiApplication(app)

        initial_ctx = WsgiMethodContext(server, {
            'QUERY_STRING': 'ccm_c_s=abc&ccm_c_i=123&ccm_i=456&ccm_s=def',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
        }, 'some-content-type')

        ctx, = server.generate_contexts(initial_ctx)
        server.get_in_object(ctx)
        server.get_out_object(ctx)
        server.get_out_string(ctx)

        out_string = ''.join(ctx.out_string)
        elt = html.fromstring(out_string)
        print html.tostring(elt, pretty_print=True)

        resp = elt.find_class('some_callResponse')
        assert len(resp) == 1
        for i in range(len(elt)):
            row = elt[i]
            if i == 0:
                cell = row.findall('th[@class="i"]')
                assert len(cell) == 1
                assert cell[0].text == 'i'

                cell = row.findall('th[@class="c_i"]')
                assert len(cell) == 1
                assert cell[0].text == 'c_i'

                cell = row.findall('th[@class="c_s"]')
                assert len(cell) == 1
                assert cell[0].text == 'c_s'

                cell = row.findall('th[@class="s"]')
                assert len(cell) == 1
                assert cell[0].text == 's'


            else:
                cell = row.findall('td[@class="i"]')
                assert len(cell) == 1
                assert cell[0].text == '456'

                cell = row.findall('td[@class="c_i"]')
                assert len(cell) == 1
                assert cell[0].text == '123'

                cell = row.findall('td[@class="c_s"]')
                assert len(cell) == 1
                assert cell[0].text == 'abc'

                cell = row.findall('td[@class="s"]')
                assert len(cell) == 1
                assert cell[0].text == 'def'
Beispiel #29
0
#

import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG)
logger = logging.getLogger('rpclib.test.interop.server.soap_http_basic')

from rpclib.server.wsgi import WsgiApplication
from rpclib.test.interop.server._service import services
from rpclib.application import Application
from rpclib.protocol.soap import Soap11
from rpclib.interface.wsdl import Wsdl11

soap_application = Application(services, 'rpclib.test.interop.server',
                               Wsdl11(), Soap11(validator='lxml'), Soap11())

if __name__ == '__main__':
    try:
        from wsgiref.simple_server import make_server
        from wsgiref.validate import validator

        wsgi_application = WsgiApplication(soap_application)
        server = make_server('0.0.0.0', 9753, validator(wsgi_application))

        logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9753))
        logger.info('WSDL is at: /?wsdl')
        server.serve_forever()

    except ImportError:
        print("Error: example server code requires Python >= 2.5")