예제 #1
0
    def test_bare(self):
        ns = {
            'wsdl':'http://schemas.xmlsoap.org/wsdl/',
            'xs':'http://www.w3.org/2001/XMLSchema',
        }

        class InteropBare(ServiceBase):
            @srpc(String, _returns=String, _body_style='bare')
            def echo_simple_bare(ss):
                return ss

            @srpc(Array(String), _returns=Array(String), _body_style='bare')
            def echo_complex_bare(ss):
                return ss

        app = Application([InteropBare], tns='tns',
                      in_protocol=Soap11(), out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())

        schema = wsdl.xpath(
                '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace]',
                namespaces=ns
            )
        assert len(schema[0].xpath(
            'xs:complexType[@name="string%s"]' % ARRAY_SUFFIX, namespaces=ns)) > 0
        elts = schema[0].xpath(
            'xs:element[@name="echo_complex_bare%s"]' % RESPONSE_SUFFIX, namespaces=ns)

        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:stringArray'
예제 #2
0
    def test_bare_simple(self):
        class SomeService(Service):
            @srpc(String, _returns=String, _body_style='bare')
            def whatever(ss):
                return ss

        app = Application([SomeService], tns='tns')
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())

        schema = wsdl.xpath(
                '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace="tns"]',
                namespaces=ns,
            )
        assert len(schema) == 1

        print(etree.tostring(wsdl, pretty_print=True))

        elts = schema[0].xpath(
            'xs:element[@name="whatever%s"]' % REQUEST_SUFFIX, namespaces=ns)
        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'xs:string'

        elts = schema[0].xpath(
            'xs:element[@name="whatever%s"]' % RESPONSE_SUFFIX, namespaces=ns)
        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'xs:string'
예제 #3
0
    def test_bare_with_conflicting_types(self):
        class SomeService(Service):
            @srpc(Array(String), _returns=Array(String))
            def whatever(sa):
                return sa
            @srpc(Array(String), _returns=Array(String), _body_style='bare')
            def whatever_bare(sa):
                return sa

        app = Application([SomeService], tns='tns')
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())
        schema, = wsdl.xpath(
                '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace="tns"]',
                namespaces=ns,
            )

        print(etree.tostring(schema, pretty_print=True))

        assert len(schema.xpath(
            'xs:complexType[@name="string%s"]' % ARRAY_SUFFIX, namespaces=ns)) > 0

        elts = schema.xpath(
            'xs:element[@name="whatever_bare%s"]' % REQUEST_SUFFIX, namespaces=ns)
        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:string%s' % ARRAY_SUFFIX

        elts = schema.xpath(
            'xs:element[@name="whatever_bare%s"]' % RESPONSE_SUFFIX, namespaces=ns)
        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:string%s' % ARRAY_SUFFIX
예제 #4
0
    def __init__(self, services, tns, name=None,
                                         in_protocol=None, out_protocol=None):
        Application.__init__(self, services, tns, name, in_protocol,
                                                                 out_protocol)

        self.event_manager.add_listener('method_call', _on_method_call)
        self.event_manager.add_listener("method_context_closed",
                                                    _on_method_context_closed)
예제 #5
0
파일: web.py 프로젝트: Bernie/spyne
    def __init__(self, services, tns, name=None, in_protocol=None,
                 out_protocol=None, db=None):
        AppBase.__init__(self, services, tns, name, in_protocol, out_protocol)

        self.event_manager.add_listener("method_call", _on_method_call)
        self.event_manager.add_listener("method_context_closed",
                                                      _on_method_context_closed)

        self.db = db
        self.Session = sessionmaker(bind=db, expire_on_commit=False)
예제 #6
0
    def test_bare_more(self):
        from spyne.test.interop.server._service import InteropBare
        app = Application([InteropBare], tns='tns',
                                    in_protocol=Soap11(), out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())

        print etree.tostring(wsdl, pretty_print=True)

        assert len(wsdl.xpath('//xs:element[@name="echo_simple_bare"]', namespaces=const_nsmap)) == 1
예제 #7
0
    def setUp(self):
        self.app = Application([SomeService], 'tns',
                                    in_protocol=Soap11(), out_protocol=Soap11())
        self.app.transport = 'test'

        self.server = WsgiApplication(self.app)
        self.wsdl = Wsdl11(self.app.interface)
        self.wsdl.build_interface_document('prot://url')
예제 #8
0
    def test_bare(self):
        ns = {
            'wsdl': 'http://schemas.xmlsoap.org/wsdl/',
            'xs': 'http://www.w3.org/2001/XMLSchema',
        }

        from spyne.model.complex import Array
        from spyne.model.primitive import String
        from spyne.protocol.soap import Soap11
        from spyne.service import ServiceBase
        from spyne.decorator import srpc
        from spyne.interface.wsdl import Wsdl11

        from lxml import etree

        class InteropBare(ServiceBase):
            @srpc(String, _returns=String, _body_style='bare')
            def echo_simple_bare(ss):
                return ss

            @srpc(Array(String), _returns=Array(String), _body_style='bare')
            def echo_complex_bare(ss):
                return ss

        app = Application([InteropBare],
                          tns='tns',
                          in_protocol=Soap11(),
                          out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())

        schema = wsdl.xpath(
            '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace]',
            namespaces=ns)
        assert len(
            schema[0].xpath('xs:complexType[@name="string%s"]' % ARRAY_SUFFIX,
                            namespaces=ns)) > 0
        elts = schema[0].xpath('xs:element[@name="echo_complex_bare%s"]' %
                               RESPONSE_SUFFIX,
                               namespaces=ns)

        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:stringArray'
예제 #9
0
파일: test_soap.py 프로젝트: mfkaptan/spyne
 def setUp(self):
     self.app = Application([MultipleReturnService],
                            'tns',
                            in_protocol=Soap11(),
                            out_protocol=Soap11())
     self.app.transport = 'none'
     self.wsdl = Wsdl11(self.app.interface)
     self.wsdl.build_interface_document('URL')
예제 #10
0
    def test_namespace_in_message_name(self):

        class S(ServiceBase):
            @srpc(String, _in_message_name='{tns}inMessageName')
            def call(s):
                pass

        app = Application([S], 'tns', 'name', Soap11(), Soap11())
예제 #11
0
 def register_service(self, service):
     spyne_app = Application([service],
                             tns=service.__target_namespace__,
                             name=service.__name__,
                             in_protocol=service.__in_protocol__,
                             out_protocol=service.__out_protocol__)
     wsgi_app = WsgiApplication(spyne_app)
     self.services[service.__service_url_path__] = wsgi_app
예제 #12
0
    def test_complex(self):
        class SomeService(ServiceBase):
            @srpc(CCM, _returns=CCM)
            def some_call(ccm):
                return ccm

        app = Application([SomeService],
                          'tns',
                          in_protocol=HttpRpc(),
                          out_protocol=HtmlTable(field_name_attr='class',
                                                 fields_as='rows'))
        server = WsgiApplication(app)

        out_string = call_wsgi_app_kwargs(server,
                                          ccm_c_s='abc',
                                          ccm_c_i='123',
                                          ccm_i='456',
                                          ccm_s='def')

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

        # Here's what this is supposed to return
        """
        <table class="some_callResponse">
            <tr>
                <th class="i">i</th>
                <td class="i">456</td>
            </tr>
            <tr>
                <th class="c_i">c_i</th>
                <td class="c_i">123</td>
            </tr>
            <tr>
                <th class="c_s">c_s</th>
                <td class="c_s">abc</td>
            </tr>
            <tr>
                <th class="s">s</th>
                <td class="s">def</td>
            </tr>
        </table>
        """

        resp = elt.find_class('some_callResponse')
        assert len(resp) == 1

        assert elt.xpath('//th[@class="i"]/text()')[0] == 'i'
        assert elt.xpath('//td[@class="i"]/text()')[0] == '456'

        assert elt.xpath('//th[@class="c_i"]/text()')[0] == 'c_i'
        assert elt.xpath('//td[@class="c_i"]/text()')[0] == '123'

        assert elt.xpath('//th[@class="c_s"]/text()')[0] == 'c_s'
        assert elt.xpath('//td[@class="c_s"]/text()')[0] == 'abc'

        assert elt.xpath('//th[@class="s"]/text()')[0] == 's'
        assert elt.xpath('//td[@class="s"]/text()')[0] == 'def'
예제 #13
0
파일: test_http.py 프로젝트: skumyol/spyne
    def test_http_headers(self):
        d = datetime(year=2013, month=1, day=1)
        string = ['hey', 'yo']

        class ResponseHeader(ComplexModel):
            _type_info = {
                'Set-Cookie': String(max_occurs='unbounded'),
                'Expires': DateTime
            }

        class SomeService(ServiceBase):
            __out_header__ = ResponseHeader

            @rpc(String)
            def some_call(ctx, s):
                assert s is not None
                ctx.out_header = ResponseHeader(**{
                    'Set-Cookie': string,
                    'Expires': d
                })

        def start_response(code, headers):
            print(headers)
            assert len([s for s in string
                        if ('Set-Cookie', s) in headers]) == len(string)
            assert dict(headers)['Expires'] == 'Tue, 01 Jan 2013 00:00:00 GMT'

        app = Application([SomeService],
                          'tns',
                          in_protocol=HttpRpc(),
                          out_protocol=HttpRpc())
        wsgi_app = WsgiApplication(app)

        req_dict = {
            'SCRIPT_NAME': '',
            'QUERY_STRING': '&s=foo',
            'PATH_INFO': '/some_call',
            'REQUEST_METHOD': 'GET',
            'SERVER_NAME': 'localhost',
            'SERVER_PORT': "9999",
            'wsgi.url_scheme': 'http',
            'wsgi.version': (1, 0),
            'wsgi.input': StringIO(),
            'wsgi.errors': StringIO(),
            'wsgi.multithread': False,
            'wsgi.multiprocess': False,
            'wsgi.run_once': True,
        }

        ret = wsgi_app(req_dict, start_response)
        print(list(ret))

        wsgi_app = wsgiref_validator(wsgi_app)

        ret = wsgi_app(req_dict, start_response)

        assert list(ret) == [b'']
예제 #14
0
    def test_fault_generation(self):
        class SoapException(ServiceBase):
            @srpc()
            def soap_exception():
                raise Fault("Client.Plausible", "A plausible fault",
                            'http://faultactor.example.com')

        app = Application([SoapException],
                          'tns',
                          in_protocol=Soap12(),
                          out_protocol=Soap12())

        req = b"""
        <soap12env:Envelope
                xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope"
                xmlns:tns="tns">
            <soap12env:Body>
                <tns:soap_exception/>
            </soap12env:Body>
        </soap12env:Envelope>
        """

        server = WsgiApplication(app)
        response = etree.fromstring(b''.join(
            server(
                {
                    'QUERY_STRING': '',
                    'PATH_INFO': '/call',
                    'REQUEST_METHOD': 'POST',
                    'CONTENT_TYPE': 'text/xml; charset=utf8',
                    'wsgi.input': BytesIO(req)
                }, start_response, "http://null")))

        response_str = etree.tostring(response, pretty_print=True)
        print(response_str)

        expected = b"""
            <soap12env:Envelope xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope">
              <soap12env:Body>
                <soap12env:Fault>
                  <soap12env:Reason>
                      <soap12env:Text xml:lang="en">A plausible fault</soap12env:Text>
                  </soap12env:Reason>
                  <soap12env:Role>http://faultactor.example.com</soap12env:Role>
                  <soap12env:Code>
                    <soap12env:Value>soap12env:Sender</soap12env:Value>
                    <soap12env:Subcode>
                      <soap12env:Value>Plausible</soap12env:Value>
                    </soap12env:Subcode>
                  </soap12env:Code>
                </soap12env:Fault>
              </soap12env:Body>
            </soap12env:Envelope>"""
        if not LXMLOutputChecker().check_output(expected, response_str,
                                                PARSE_XML):
            raise Exception("Got: %s but expected: %s" %
                            (response_str, expected))
예제 #15
0
    def test_imports(self):
        import logging
        logging.basicConfig(level=logging.DEBUG)

        class KeyValuePair(ComplexModel):
            __namespace__ = "1"
            key = Unicode
            value = Unicode

        class Something(ComplexModel):
            __namespace__ = "2"
            d = DateTime
            i = Integer

        class SomethingElse(ComplexModel):
            __namespace__ = "3"
            a = AnyXml
            b = UnsignedLong
            s = Something

        class BetterSomething(Something):
            __namespace__ = "4"
            k = UnsignedInteger16

        class Service1(ServiceBase):
            @rpc(SomethingElse, _returns=Array(KeyValuePair))
            def some_call(ctx, sth):
                pass

        class Service2(ServiceBase):
            @rpc(BetterSomething, _returns=Array(KeyValuePair))
            def some_other_call(ctx, sth):
                pass

        application = Application([Service1, Service2],
                                  in_protocol=HttpRpc(),
                                  out_protocol=Soap11(),
                                  name='Service',
                                  tns='target_namespace')

        imports = application.interface.imports
        tns = application.interface.get_tns()
        smm = application.interface.service_method_map
        print(imports)

        assert imports[tns] == set(['1', '3', '4'])
        assert imports['3'] == set(['2'])
        assert imports['4'] == set(['2'])

        assert smm['{%s}some_call' % tns]
        assert smm['{%s}some_call' % tns][0][0] == Service1
        assert smm['{%s}some_call' % tns][0][1].function == Service1.some_call

        assert smm['{%s}some_other_call' % tns]
        assert smm['{%s}some_other_call' % tns][0][0] == Service2
        assert smm['{%s}some_other_call' %
                   tns][0][1].function == Service2.some_other_call
예제 #16
0
def geometry_service(fcgi=True):
    if fcgi is False:
        def _on_method_return_object(ctx):
            ctx.transport.resp_headers['Access-Control-Allow-Origin'] = "*"
            ctx.transport.resp_headers['Cache-Control'] = "public,max-age=86400" # tbd

        GeometryService.event_manager.add_listener('method_return_object',
                                                   _on_method_return_object)

    json = Application([GeometryService], tns='swhv.service.geometry.json',
                       in_protocol=HttpRpc(validator='soft'),
                       out_protocol=JsonDocument())

    msgpack = Application([GeometryService], tns='swhv.service.geometry.msgpack',
                          in_protocol=HttpRpc(validator='soft'),
                          out_protocol=MessagePackDocument())

    return WsgiMounter({'json': json, 'msgpack': msgpack})
예제 #17
0
    def test_single_method(self):
        try:
            Application([MultipleMethods1,MultipleMethods2], 'tns', in_protocol=Soap11(), out_protocol=Soap11())

        except ValueError:
            pass

        else:
            raise Exception('must fail.')
예제 #18
0
    def setUp(self):
        self.app = Application([TestService], 'tns', in_protocol=Soap12(), out_protocol=Soap12())
        self.app.transport = 'null.spyne'
        self.srv = TestService()

        wsdl = Wsdl11(self.app.interface)
        wsdl.build_interface_document('URL')
        self.wsdl_str = wsdl.get_interface_document()
        self.wsdl_doc = etree.fromstring(self.wsdl_str)
예제 #19
0
 def __init__(self):
     from wsgiref.simple_server import make_server
     self.application = Application(
         [RPCReceiver.HelloSwitchService],
         tns='spyne.examples.hello',
         in_protocol=HttpRpc(validator='soft'),
         out_protocol=JsonDocument())
     self.wsgi_app = WsgiApplication(self.application)
     self.server = make_server('0.0.0.0', 7846, self.wsgi_app)
예제 #20
0
    def __init__(self, client):
        def _map_context(ctx):
            ctx.udc = UserDefinedContext(client)

        self.app = Application([SwitchPower],
                               tns=SwitchPower.tns,
                               in_protocol=Soap11(validator='lxml'),
                               out_protocol=Soap11())
        self.app.event_manager.add_listener('method_call', _map_context)
예제 #21
0
def xgj_main_task():
    application = Application([DRMSService],
                              'http://webservice.ack.dns.act.com/',
                              in_protocol=Soap11(validator='lxml'),
                              out_protocol=Soap11())

    wsgi_app = WsgiMounter({'DNSWebService': application})
    server = make_server('0.0.0.0', listen_port, wsgi_app)
    server.serve_forever()
예제 #22
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(c=ccm.c,i=ccm.i, s=ccm.s)] * 2

        app = Application([SomeService], 'tns',
                                            in_protocol=HttpRpc(hier_delim='_'),
                                            out_protocol=HtmlMicroFormat())
        server = WsgiApplication(app)

        out_string = call_wsgi_app_kwargs(server,
                             ccm_c_s='abc', ccm_c_i=123, ccm_i=456, ccm_s='def')

        #
        # Here's what this is supposed to return:
        #
        # <div class="some_callResponse"><div class="some_callResult">
        #     <div class="CCM">
        #         <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 class="CCM">
        #         <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></div>
        #

        print(out_string)
        elt = html.fromstring(out_string)
        show(elt, "TestHtmlMicroFormat.test_complex_array")

        resp = elt.find_class('some_callResponse')
        assert len(resp) == 1
        res = resp[0].find_class('some_callResult')
        assert len(res) == 1

        assert len(res[0].find_class("CCM")) == 2
예제 #23
0
    def test_rpc(self):
        data = {"a":"b", "c": "d"}

        class KeyValuePair(ComplexModel):
            key = Unicode
            value = Unicode

        class SomeService(Service):
            @rpc(String(max_occurs='unbounded'),
                    _returns=Array(KeyValuePair),
                    _in_variable_names={
                        'keys': 'key'
                    }
                )
            def get_values(ctx, keys):
                for k in keys:
                    yield KeyValuePair(key=k, value=data[k])

        application = Application([SomeService],
            in_protocol=MessagePackRpc(),
            out_protocol=MessagePackRpc(ignore_wrappers=False),
            name='Service', tns='tns')
        server = WsgiApplication(application)

        input_string = msgpack.packb([0, 0, "get_values", [["a", "c"]]])
        input_stream = BytesIO(input_string)

        ret = server({
            'CONTENT_LENGTH': str(len(input_string)),
            'CONTENT_TYPE': 'application/x-msgpack',
            'HTTP_CONNECTION': 'close',
            'HTTP_CONTENT_LENGTH': str(len(input_string)),
            'HTTP_CONTENT_TYPE': 'application/x-msgpack',
            'PATH_INFO': '/',
            'QUERY_STRING': '',
            'SERVER_NAME': 'localhost',
            'SERVER_PORT': '7000',
            'REQUEST_METHOD': 'POST',
            'wsgi.url_scheme': 'http',
            'wsgi.input': input_stream,
        }, start_response)

        ret = b''.join(ret)
        print(repr(ret))
        ret = msgpack.unpackb(ret)
        print(repr(ret))

        s = [1, 0, None, {b'get_valuesResponse': {
            b'get_valuesResult': [
                  {b"KeyValuePair": {b'key': b'a', b'value': b'b'}},
                  {b"KeyValuePair": {b'key': b'c', b'value': b'd'}},
                ]
            }}
        ]
        print(s)
        assert ret == s
예제 #24
0
파일: service.py 프로젝트: kstain/SOC15F
 def __init__(self, *args, **kargs):
   password = kargs.pop('_mypassword')
   host = kargs.pop('_myhost')
   username = kargs.pop('_username')
   database = kargs.pop('_database')
   xml_path = kargs.pop('_xmlpath')
   Application.__init__(self, *args, **kargs)
   assert not hasattr(self, '_password')
   assert not hasattr(self, '_host')
   assert not hasattr(self, '_username')
   self._db=DBLPDatabaseDriver(host=host,
                               username=username,
                               password=password,
                               database=database,
                               create_db_on_start=True)
   self._db.create_table()
   parser = DBLPParser(xml_path)
   parser.visit()
   parser.push_to_db(self._db)
예제 #25
0
    def test_array_iterable(self):
        class SomeService(Service):
            @rpc(Array(Unicode), Iterable(Unicode))
            def some_call(ctx, a, b):
                pass

        app = Application([SomeService], 'tns', in_protocol=Soap11(),
                                   out_protocol=Soap11(cleanup_namespaces=True))

        server = WsgiApplication(app)
예제 #26
0
    def setUp(self):
        class SomeService(ServiceBase):
            @rpc(Unicode)
            def some_call(ctx, some_str):
                print(some_str)


        app = Application([SomeService], "some_tns", in_protocol=Soap11(),
                                                     out_protocol=Soap11())
        self.wsgi_app = WsgiApplication(app)
예제 #27
0
파일: main.py 프로젝트: mfkaptan/spynepi
    def call_wrapper(self, ctx):
        """This is the application-wide exception transforming function."""

        try:
            return Application.call_wrapper(self, ctx)

        except NoResultFound, e:
            logger.exception(e)
            ctx.out_string = ["Resource not found"]
            raise ResourceNotFoundError()  # Return HTTP 404
예제 #28
0
파일: main.py 프로젝트: pombredanne/spynepi
    def call_wrapper(self, ctx):
        """This is the application-wide exception transforming function."""

        try:
            return Application.call_wrapper(self, ctx)

        except NoResultFound, e:
            logger.exception(e)
            ctx.out_string = ["Resource not found"]
            raise ResourceNotFoundError() # Return HTTP 404
예제 #29
0
def service_factory(service):
    u"""
    Оборачивает класс сервиса в приложение django c basic auth
    """

    application_tns = service.application_tns if hasattr(
        service, 'application_tns') else 'smartbps'
    service_name = service.service_name if hasattr(
        service, 'service_name') else service.__name__.lower()

    # 20 Мб
    max_content_length = (1024 * 1024 * 20)
    app = DjangoApplication(Application([service],
                                        tns=application_tns,
                                        name='smartbps',
                                        in_protocol=Soap11(validator='lxml'),
                                        out_protocol=Soap11()),
                            max_content_length=max_content_length)

    @csrf_exempt
    def service_wrapper(request):
        u"""
        При не авторизованном запросе (смотрим по сессии),
        выдаем запрос на авторизацию http401
        При получении ответа, запоминаем в сессию логин и пароль.
        Если в сессии есть логин-пароль, то проверяем его при каждом запросе
        (а вдруг поддерживается длинная сессия и пароль нужно поменять)
        """

        key = 'web_service:auth_%s' % service_name

        # Авторизован
        if key in request.session:
            uname, passwd = request.session[key]
            if uname == service.login and passwd == service.password:
                return app(request)

        # Обработка запроса авторизации
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                method, user_pass = auth
                if method == "Basic":
                    uname, passwd = base64.b64decode(user_pass).split(':')
                    if uname == service.login and passwd == service.password:
                        request.session[key] = [uname, passwd]
                        return app(request)

        # Нужно отправить запрос на авторизацию
        response = HttpResponse()
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="soap_%s"' % service_name
        return response

    return service_wrapper
예제 #30
0
    def test_complex_array(self):
        class SomeService(ServiceBase):
            @srpc(CCM, _returns=Array(CCM))
            def some_call(ccm):
                return [ccm] * 5

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

        out_string = call_wsgi_app_kwargs(
            server,
            ccm_i='456',
            ccm_s='def',
            ccm_c_i='123',
            ccm_c_s='abc',
        )

        from lxml import etree
        elt = etree.fromstring(out_string)
        print(etree.tostring(elt, pretty_print=True))

        elt = html.fromstring(out_string)
        resp = elt.find_class('some_callResponse')
        assert len(resp) == 1

        row, = elt[0]  # thead
        cell = row.findall('th[@class="i"]')
        assert len(cell) == 1
        assert cell[0].text == 'i'

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

        for row in elt[1]:  # tbody
            cell = row.xpath('td[@class="i"]')
            assert len(cell) == 1
            assert cell[0].text == '456'

            cell = row.xpath('td[@class="c"]//td[@class="i"]')
            assert len(cell) == 1
            assert cell[0].text == '123'

            cell = row.xpath('td[@class="c"]//td[@class="s"]')
            assert len(cell) == 1
            assert cell[0].text == 'abc'

            cell = row.xpath('td[@class="s"]')
            assert len(cell) == 1
            assert cell[0].text == 'def'
예제 #31
0
 def register_service(self, service):
     spyne_app = Application([service],
                             tns=service.__target_namespace__,
                             name=service.__name__,
                             in_protocol=service.__in_protocol__,
                             out_protocol=service.__out_protocol__)
     spyne_app.event_manager.add_listener('method_call',
                                          self._on_method_call)
     spyne_app.event_manager.add_listener('method_return_object',
                                          self._on_method_return_object)
     wsgi_app = WsgiApplication(spyne_app)
     self.services[service.__service_url_path__] = wsgi_app
예제 #32
0
    def test_mtom_join_envelope_chunks(self):
        FILE_NAME = 'EA055406-5881-4F02-A3DC-9A5A7510D018.dat'
        TNS = 'http://gib.gov.tr/vedop3/eFatura'

        # large enough payload to be chunked
        PAYLOAD = b"sample data " * 1024

        class SomeService(Service):
            @rpc(Unicode(sub_name="fileName"),
                 ByteArray(sub_name='binaryData'),
                 ByteArray(sub_name="hash"),
                 _returns=Unicode)
            def documentRequest(ctx, file_name, file_data, data_hash):
                assert file_name == FILE_NAME
                assert file_data == (PAYLOAD, )

                return file_name

        app = Application([SomeService],
                          tns=TNS,
                          in_protocol=Soap12(),
                          out_protocol=Soap12())

        server = WsgiApplication(app, block_length=1024)
        response = etree.fromstring(b''.join(
            server(
                {
                    'QUERY_STRING':
                    '',
                    'PATH_INFO':
                    '/call',
                    'REQUEST_METHOD':
                    'POST',
                    'CONTENT_TYPE':
                    'Content-Type: multipart/related; '
                    'type="application/xop+xml"; '
                    'boundary="uuid:2e53e161-b47f-444a-b594-eb6b72e76997"; '
                    'start="<*****@*****.**>"; '
                    'start-info="application/soap+xml"; action="sendDocument"',
                    'wsgi.input':
                    BytesIO(
                        MTOM_REQUEST.replace(b"\n", b"\r\n").replace(
                            b"sample data", PAYLOAD)),
                }, start_response, "http://null")))

        response_str = etree.tostring(response, pretty_print=True)
        print(response_str)

        nsdict = dict(tns=TNS)

        assert etree.fromstring(response_str) \
            .xpath(".//tns:documentRequestResult/text()", namespaces=nsdict) \
                                                                  == [FILE_NAME]
예제 #33
0
    def setUp(self):
        class SomeService(ServiceBase):
            @srpc(String, _returns=String)
            def echo_string(s):
                return s

        app = Application([SomeService], 'tns',
                in_protocol=HttpRpc(validator='soft'),
                out_protocol=HttpRpc(),
            )

        self.app = WsgiApplication(app)
예제 #34
0
    def test_bare_with_conflicting_types(self):
        class SomeService(Service):
            @srpc(Array(String), _returns=Array(String))
            def whatever(sa):
                return sa

            @srpc(Array(String), _returns=Array(String), _body_style='bare')
            def whatever_bare(sa):
                return sa

        app = Application([SomeService], tns='tns')
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')
        wsdl = etree.fromstring(wsdl.get_interface_document())
        schema, = wsdl.xpath(
            '/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace="tns"]',
            namespaces=ns,
        )

        print(etree.tostring(schema, pretty_print=True))

        assert len(schema.xpath(
            'xs:complexType[@name="string%s"]' % ARRAY_SUFFIX,
                                                             namespaces=ns)) > 0

        elts = schema.xpath(
            'xs:element[@name="whatever_bare%s"]' % REQUEST_SUFFIX,
                                                                  namespaces=ns)

        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:string%s' % ARRAY_SUFFIX

        elts = schema.xpath(
            'xs:element[@name="whatever_bare%s"]' % RESPONSE_SUFFIX,
                                                                  namespaces=ns)

        assert len(elts) > 0
        assert elts[0].attrib['type'] == 'tns:string%s' % ARRAY_SUFFIX
예제 #35
0
파일: _service.py 프로젝트: zhuhj89/spyne
def initialize(services, tns='spyne.examples.twisted.resource'):
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)

    observer = log.PythonLoggingObserver('twisted')
    log.startLoggingWithObserver(observer.emit, setStdout=False)

    application = Application(services,
                              'spyne.examples.twisted.hello',
                              in_protocol=HttpRpc(),
                              out_protocol=HttpRpc())

    return application
예제 #36
0
파일: SOAPBinding.py 프로젝트: poses/erp5
 def _getServer(self):
   try:
     serial, server = self._v_server
     if serial == self._p_serial:
       return server
   except AttributeError:
     pass
   server = HttpBase(Application(
     map(self._service_class_dict.__getitem__, self.getServiceClassList()),
     self.getTargetNamespace(),
     in_protocol=Soap11(), out_protocol=Soap11()))
   self._v_server = self._p_serial, server
   return server
예제 #37
0
    def test_invalid_name(self):
        class Service(ServiceBase):
            @srpc()
            def XResponse():
                pass

        try:
            Application([Service], 'hey', in_protocol=XmlDocument(),
                                          out_protocol=XmlDocument())
        except:
            pass
        else:
            raise Exception("must fail.")
예제 #38
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)

    services = (SomeService, SomeAuxService)
    application = Application(services, 'spyne.examples.auxproc',
                                in_protocol=HttpRpc(), out_protocol=XmlDocument())

    server = make_server(host, port, WsgiApplication(application))

    logging.info("listening to http://%s:%d" % (host, port))

    return server.serve_forever()
예제 #39
0
    def test_attribute_of(self):
        class SomeObject(ComplexModel):
            c = String
            a = XmlAttribute(Integer, attribute_of='c')

        class SomeService(ServiceBase):
            @srpc(SomeObject)
            def echo_simple_bare(ss):
                pass

        app = Application([SomeService], tns='tns',
                                    in_protocol=Soap11(), out_protocol=Soap11())
        app.transport = 'None'

        wsdl = Wsdl11(app.interface)
        wsdl.build_interface_document('url')

        wsdl = etree.fromstring(wsdl.get_interface_document())
        print(etree.tostring(wsdl, pretty_print=True))
        assert len(wsdl.xpath(
            "/wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='%s']"
            "/xs:complexType[@name='SomeObject']/xs:sequence/xs:element[@name='c']"
            '/xs:complexType/xs:simpleContent/xs:extension/xs:attribute[@name="a"]'
            % (SomeObject.get_namespace()), namespaces=const_nsmap)) > 0
예제 #40
0
파일: regen_wsdl.py 프로젝트: Bernie/spyne
#!/usr/bin/env python

from lxml import etree
from spyne.test.sort_wsdl import sort_wsdl
from spyne.interface.wsdl import Wsdl11

from spyne.test.interop.server._service import services
from spyne.application import Application

app = Application(services, 'spyne.test.interop.server')
app.transport = 'http://schemas.xmlsoap.org/soap/http'
wsdl = Wsdl11(app.interface)
wsdl.build_interface_document('http://localhost:9754/')
elt = etree.ElementTree(etree.fromstring(wsdl.get_interface_document()))
sort_wsdl(elt)
s = etree.tostring(elt)

# minidom's serialization seems to put attributes in alphabetic order.
# this is exactly what we want here.
from xml.dom.minidom import parseString
doc = parseString(s)
s = doc.toprettyxml(indent='  ', newl='\n', encoding='utf8')
s = s.replace(" xmlns:","\n                  xmlns:")

open('wsdl.xml', 'w').write(s)
print 'wsdl.xml written'
예제 #41
0
파일: __init__.py 프로젝트: 1-bit/spyne
def build_app(service_list, tns, name):
    app = Application(service_list, tns, name=name,
                      in_protocol=Soap11(), out_protocol=Soap11())
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    return app
예제 #42
0
파일: service.py 프로젝트: kstain/SOC15F
 def __init__(self, *args, **kargs):
   xslt_path = kargs.pop('_xslt')
   Application.__init__(self, *args, **kargs)
   xslt = etree.parse(xslt_path)
   self.transform = etree.XSLT(xslt)
예제 #43
0
파일: __init__.py 프로젝트: 66ru/spyne
def build_app(service_list, tns, name):
    app = Application(service_list, tns, Wsdl11(),
                      Soap11(), Soap11(), name=name)
    app.transport = 'http://schemas.xmlsoap.org/soap/http'
    return app