Exemple #1
0
    def test_boolean(self):
        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, True, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.text)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, 0, b, ns_test)
        b = b[0]
        self.assertEquals('false', b.text)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, 1, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.text)

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, True)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, False, b, ns_test)
        b = b[0]
        self.assertEquals('false', b.text)

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, False)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, None, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.get('{%s}nil' % ns.xsi))

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, None)
Exemple #2
0
def get_xml_as_object(elt, cls):
    '''Returns a native :class:`spyne.model.complex.ComplexModel` child from an
    ElementTree representation of the same class.

    :param value: The class the xml document represents.
    :param value: The xml document to be deserialized.
    '''

    xml_object = XmlDocument()

    return xml_object.from_element(cls, elt)
Exemple #3
0
    def __init__(self, app=None, validator=None, wrapped=True,
                                xml_declaration=True, cleanup_namespaces=True):
        XmlDocument.__init__(self, app, validator, xml_declaration,
                                                             cleanup_namespaces)

        self.__wrapped = wrapped

        # SOAP requires DateTime strings to be in iso format. This function
        # bypasses datetime formatting via DateTime(format="...") string.
        self.serialization_handlers[DateTime] = _datetime_to_parent_element
        self.deserialization_handlers[DateTime] = _datetime_from_element
Exemple #4
0
    def __init__(self, app=None, validator=None, xml_declaration=True,
                cleanup_namespaces=True, encoding='UTF-8', pretty_print=False):
        XmlDocument.__init__(self, app, validator, xml_declaration,
                                    cleanup_namespaces, encoding, pretty_print)

        # SOAP requires DateTime strings to be in iso format. The following
        # lines make sure custom datetime formatting via DateTime(format="...")
        # string is bypassed.
        self._to_string_handlers[Time] = lambda cls, value: value.isoformat()
        self._to_string_handlers[DateTime] = lambda cls, value: value.isoformat()

        self._from_string_handlers[Date] = date_from_string_iso
        self._from_string_handlers[DateTime] = datetime_from_string_iso
Exemple #5
0
    def test_datetime_timezone(self):
        import pytz

        n = datetime.datetime.now(pytz.timezone('EST'))
        element = etree.Element('test')
        cls = DateTime(as_timezone=pytz.utc, timezone=False)
        XmlDocument().to_parent(None, cls, n, element, ns_test)
        element = element[0]

        c = n.astimezone(pytz.utc).replace(tzinfo=None)
        self.assertEquals(element.text, c.isoformat())
        dt = XmlDocument().from_element(None, cls, element)
        assert dt.tzinfo is not None
        dt = dt.replace(tzinfo=None)
        self.assertEquals(c, dt)
    def test_serialize_simple_array(self):
        t = Test(days=[
            DaysOfWeekEnum.Monday,
            DaysOfWeekEnum.Tuesday,
            DaysOfWeekEnum.Wednesday,
            DaysOfWeekEnum.Thursday,
            DaysOfWeekEnum.Friday,
            DaysOfWeekEnum.Saturday,
            DaysOfWeekEnum.Sunday,
        ])

        Test.resolve_namespace(Test, 'tns')

        elt = etree.Element('test')
        XmlDocument().to_parent(None, Test, t, elt, 'test_namespace')
        elt = elt[0]

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

        ret = XmlDocument().from_element(None, Test, elt)
        self.assertEquals(t.days, ret.days)
Exemple #7
0
    def test_simple_array(self):
        class cls(ComplexModel):
            __namespace__ = 'tns'
            s = Unicode(max_occurs='unbounded')

        val = cls(s=['a', 'b'])

        parent = etree.Element('parent')
        XmlDocument().to_parent(None, cls, val, parent, 'tns')
        print(etree.tostring(parent, pretty_print=True))
        xpath = parent.xpath('//x:cls/x:s/text()', namespaces={'x': 'tns'})
        assert xpath == val.s
Exemple #8
0
    def test_attribute_of(self):
        class C(ComplexModel):
            a = Unicode
            b = XmlAttribute(Unicode, attribute_of="a")

        class SomeService(ServiceBase):
            @srpc(C, _returns=C)
            def some_call(c):
                assert c.a == 'a'
                assert c.b == 'b'
                return c

        app = Application([SomeService],
                          "tns",
                          name="test_attribute_of",
                          in_protocol=XmlDocument(),
                          out_protocol=XmlDocument())
        server = ServerBase(app)

        initial_ctx = MethodContext(server)
        initial_ctx.in_string = [
            '<some_call xmlns="tns">'
            '<c>'
            '<a b="b">a</a>'
            '</c>'
            '</some_call>'
        ]

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

        ret = etree.fromstring(''.join(ctx.out_string)).xpath(
            '//s0:a', namespaces=app.interface.nsmap)[0]

        print etree.tostring(ret, pretty_print=True)

        assert ret.text == "a"
        assert ret.attrib['b'] == "b"
Exemple #9
0
def initialize(services=(SomeService, )):
    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.hello.twisted',
                              in_protocol=HttpRpc(),
                              out_protocol=XmlDocument())

    return application
Exemple #10
0
def get_object_as_xml(value, cls=None, root_tag_name=None, no_namespace=False):
    '''Returns an ElementTree representation of a
    :class:`spyne.model.complex.ComplexModel` subclass.

    :param value: The instance of the class to be serialized.
    :param value: The root tag string to use. Defaults to the output of
        ``value.__class__.get_type_name_ns()``.
    '''

    if cls is None:
        cls = value.__class__
    xml_object = XmlDocument()
    parent = etree.Element("parent")

    xml_object.to_parent_element(cls, value, cls.get_namespace(),
                                                          parent, root_tag_name)

    if no_namespace:
        _dig(parent)
        etree.cleanup_namespaces(parent)

    return parent[0]
Exemple #11
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()
Exemple #12
0
def get_object_as_xml(value, cls=None, root_tag_name=None, no_namespace=False):
    '''Returns an ElementTree representation of a :class:`spyne.model.complex.ComplexModel`
    child.

    :param value: The instance of the class to be serialized.
    :param value: The root tag string to use. Defaults to the output of
        ``value.__class__.get_type_name_ns()``.
    '''

    if cls is None:
        cls = value.__class__
    xml_object = XmlDocument()
    parent = etree.Element("parent")

    xml_object.to_parent_element(cls, value, cls.get_namespace(),
                                                          parent, root_tag_name)

    if no_namespace:
        _dig(parent)
        etree.cleanup_namespaces(parent)

    return parent[0]
Exemple #13
0
    def test_method_exception(self):
        from spyne.protocol.xml import XmlDocument

        h = [0]

        def on_method_exception_object(ctx):
            assert ctx.out_error is not None
            from spyne.protocol.xml import SchemaValidationError
            assert isinstance(ctx.out_error, SchemaValidationError)
            logging.error(repr(ctx.out_error))
            h[0] += 1

        class SomeService(Service):
            @rpc(Unicode(5))
            def some_call(ctx, some_str):
                print(some_str)

        app = Application([SomeService], "some_tns",
               in_protocol=XmlDocument(validator='lxml'), out_protocol=Soap11())

        app.event_manager.add_listener(
                          "method_exception_object", on_method_exception_object)

        # this shouldn't be called because:
        # 1. document isn't validated
        # 2. hence; document can't be parsed
        # 3. hence; document can't be mapped to a function
        # 4. hence; document can't be mapped to a service class
        # 5. hence; no handlers from the service class is invoked.
        # 6. hence; the h[0] == 1 check (instead of 2)
        SomeService.event_manager.add_listener(
                          "method_exception_object", on_method_exception_object)

        wsgi_app = WsgiApplication(app)

        xml_request = b"""
            <tns:some_call xmlns:tns="some_tns">
                <tns:some_str>123456</tns:some_str>
            </tns:some_call>
        """

        _ = b''.join(wsgi_app({
            'PATH_INFO': '/',
            'SERVER_NAME': 'localhost',
            'SERVER_PORT': '7000',
            'REQUEST_METHOD': 'POST',
            'wsgi.url_scheme': 'http',
            'wsgi.input': BytesIO(xml_request),
        }, start_response))

        assert h[0] == 1
Exemple #14
0
    def test_mandatory_element_attributes(self):
        class C(ComplexModel):
            bar = XmlAttribute(M(Unicode))

        class SomeService(ServiceBase):
            @srpc(C.customize(min_occurs=1), _returns=Unicode)
            def some_call(c):
                assert c is not None
                assert hasattr(c, 'foo')
                assert c.foo == 'hello'
                return c.foo

        app = Application([SomeService],
                          "tns",
                          name="test_mandatory_element_attributes",
                          in_protocol=XmlDocument(validator='lxml'),
                          out_protocol=XmlDocument())
        server = ServerBase(app)

        ctx = self._get_ctx(
            server,
            [
                b'<some_call xmlns="tns">'
                # no mandatory elements at all...
                b'</some_call>'
            ])
        self.assertRaises(SchemaValidationError, server.get_out_object, ctx)

        ctx = self._get_ctx(
            server,
            [
                b'<some_call xmlns="tns">'
                b'<c>'
                # no mandatory elements here...
                b'</c>'
                b'</some_call>'
            ])
        self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
Exemple #15
0
    def test_serialize_complex_array(self):
        days = [
            DaysOfWeekEnum.Monday,
            DaysOfWeekEnum.Tuesday,
            DaysOfWeekEnum.Wednesday,
            DaysOfWeekEnum.Thursday,
            DaysOfWeekEnum.Friday,
            DaysOfWeekEnum.Saturday,
            DaysOfWeekEnum.Sunday,
        ]

        days_xml = [
            ('{tns}DaysOfWeekEnum', 'Monday'),
            ('{tns}DaysOfWeekEnum', 'Tuesday'),
            ('{tns}DaysOfWeekEnum', 'Wednesday'),
            ('{tns}DaysOfWeekEnum', 'Thursday'),
            ('{tns}DaysOfWeekEnum', 'Friday'),
            ('{tns}DaysOfWeekEnum', 'Saturday'),
            ('{tns}DaysOfWeekEnum', 'Sunday'),
        ]

        DaysOfWeekEnumArray = Array(DaysOfWeekEnum)
        DaysOfWeekEnumArray.__namespace__ = 'tns'

        elt = etree.Element('test')
        XmlDocument().to_parent(None, DaysOfWeekEnumArray, days, elt,
                                'test_namespace')

        elt = elt[0]
        ret = XmlDocument().from_element(None, Array(DaysOfWeekEnum), elt)
        assert days == ret

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

        pprint(self.app.interface.nsmap)
        assert days_xml == [(e.tag, e.text) for e in elt.xpath(
            '//tns:DaysOfWeekEnum', namespaces=self.app.interface.nsmap)]
Exemple #16
0
    def test_xml_data(self):
        class C(ComplexModel):
            a = XmlData(Unicode)
            b = XmlAttribute(Unicode)

        class SomeService(Service):
            @srpc(C, _returns=C)
            def some_call(c):
                assert c.a == 'a'
                assert c.b == 'b'
                return c

        app = Application([SomeService], "tns", name="test_xml_data",
                        in_protocol=XmlDocument(), out_protocol=XmlDocument())
        server = ServerBase(app)
        initial_ctx = MethodContext(server, MethodContext.SERVER)
        initial_ctx.in_string = [
            b'<some_call xmlns="tns">'
                b'<c b="b">a</c>'
            b'</some_call>'
        ]

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

        print(ctx.out_string)
        pprint(app.interface.nsmap)

        ret = etree.fromstring(b''.join(ctx.out_string)).xpath(
            '//tns:some_call' + RESULT_SUFFIX, namespaces=app.interface.nsmap)[0]

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

        assert ret.text == "a"
        assert ret.attrib['b'] == "b"
Exemple #17
0
    def test_mandatory_elements(self):
        class SomeService(ServiceBase):
            @srpc(M(Unicode), _returns=Unicode)
            def some_call(s):
                assert s == 'hello'
                return s

        app = Application([SomeService],
                          "tns",
                          name="test_mandatory_elements",
                          in_protocol=XmlDocument(validator='lxml'),
                          out_protocol=XmlDocument())
        server = ServerBase(app)

        # Valid call with all mandatory elements in
        ctx = self._get_ctx(
            server,
            [b'<some_call xmlns="tns">'
             b'<s>hello</s>'
             b'</some_call>'])
        server.get_out_object(ctx)
        server.get_out_string(ctx)
        ret = etree.fromstring(b''.join(ctx.out_string)).xpath(
            '//tns:some_call%s/text()' % RESULT_SUFFIX,
            namespaces=app.interface.nsmap)[0]
        assert ret == 'hello'

        # Invalid call
        ctx = self._get_ctx(
            server,
            [
                b'<some_call xmlns="tns">'
                # no mandatory elements here...
                b'</some_call>'
            ])
        self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
Exemple #18
0
    def test_call(self):
        queue = set()

        class MessageService(ServiceBase):
            @srpc(String, String)
            def send_message(s, k):
                queue.add((s,k))

        application = Application([MessageService], 'some_tns',
                          in_protocol=XmlDocument(), out_protocol=XmlDocument())

        server = NullServer(application)

        queue.clear()
        server.service.send_message("zabaaa", k="hobaa")
        assert set([("zabaaa","hobaa")]) == queue

        queue.clear()
        server.service.send_message(k="hobaa")
        assert set([(None,"hobaa")]) == queue

        queue.clear()
        server.service.send_message("zobaaa", s="hobaa")
        assert set([("hobaa", None)]) == queue
Exemple #19
0
    def test_attribute_ns(self):
        class a(ComplexModel):
            b = Unicode
            c = XmlAttribute(Unicode, ns="spam", attribute_of="b")

        class SomeService(ServiceBase):
            @srpc(_returns=a)
            def some_call():
                return a(b="foo",c="bar")

        app = Application([SomeService], "tns", in_protocol=XmlDocument(),
                                                out_protocol=XmlDocument())
        server = ServerBase(app)
        initial_ctx = MethodContext(server)
        initial_ctx.in_string = ['<some_call xmlns="tns"/>']

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

        elt = etree.fromstring(''.join(ctx.out_string))
        target = elt.xpath('//s0:b', namespaces=app.interface.nsmap)[0]
        assert target.attrib['{%s}c' % app.interface.nsmap["s1"]] == "bar"
Exemple #20
0
    def test_to_parent_element_wo_detail(self):
        from lxml.etree import Element
        import spyne.const.xml_ns
        ns_soap_env = spyne.const.xml_ns.soap_env

        element = Element('testing')
        fault = Fault()
        cls = Fault

        XmlDocument().to_parent_element(cls, fault, 'urn:ignored', element)

        (child,) = element.getchildren()
        self.assertEqual(child.tag, '{%s}Fault' % ns_soap_env)
        self.assertEqual(child.find('faultcode').text, 'senv:Server')
        self.assertEqual(child.find('faultstring').text, 'Fault')
        self.assertEqual(child.find('faultactor').text, '')
        self.failIf(child.findall('detail'))
Exemple #21
0
    def test_from_xml_w_detail(self):
        from lxml.etree import Element
        from lxml.etree import SubElement
        from spyne.const.xml import SOAP11_ENV

        element = Element(SOAP11_ENV('Fault'))
        fcode = SubElement(element, 'faultcode')
        fcode.text = 'soap11env:other'
        fstr = SubElement(element, 'faultstring')
        fstr.text = 'Testing'
        actor = SubElement(element, 'faultactor')
        actor.text = 'phreddy'
        detail = SubElement(element, 'detail')

        fault = XmlDocument().from_element(None, Fault, element)

        self.assertTrue(fault.detail is detail)
Exemple #22
0
    def test_to_parent_wo_detail(self):
        from lxml.etree import Element
        import spyne.const.xml
        ns_soap_env = spyne.const.xml.NS_SOAP11_ENV
        soap_env = spyne.const.xml.PREFMAP[spyne.const.xml.NS_SOAP11_ENV]

        element = Element('testing')
        fault = Fault()
        cls = Fault

        XmlDocument().to_parent(None, cls, fault, element, 'urn:ignored')

        (child,) = element.getchildren()
        self.assertEqual(child.tag, '{%s}Fault' % ns_soap_env)
        self.assertEqual(child.find('faultcode').text, '%s:Server' % soap_env)
        self.assertEqual(child.find('faultstring').text, 'Fault')
        self.assertEqual(child.find('faultactor').text, '')
        self.assertFalse(child.findall('detail'))
Exemple #23
0
def simple_get_restriction_tag(document, cls):
    extends = _check_extension_attrs(cls)
    if extends is None:
        return

    simple_type = etree.Element(XSD('simpleType'))

    simple_type.set('name', cls.get_type_name())
    document.add_simple_type(cls, simple_type)

    restriction = etree.SubElement(simple_type, XSD('restriction'))
    restriction.set('base', extends.get_type_name_ns(document.interface))

    for v in cls.Attributes.values:
        enumeration = etree.SubElement(restriction, XSD('enumeration'))
        enumeration.set('value', XmlDocument().to_unicode(cls, v))

    return restriction
Exemple #24
0
    def test_from_xml_w_detail(self):
        from lxml.etree import Element
        from lxml.etree import SubElement
        import spyne.const.xml_ns
        ns_soap_env = spyne.const.xml_ns.soap11_env

        element = Element('{%s}Fault' % ns_soap_env)
        fcode = SubElement(element, 'faultcode')
        fcode.text = 'soap11env:other'
        fstr = SubElement(element, 'faultstring')
        fstr.text = 'Testing'
        actor = SubElement(element, 'faultactor')
        actor.text = 'phreddy'
        detail = SubElement(element, 'detail')

        fault = XmlDocument().from_element(None, Fault, element)

        self.failUnless(fault.detail is detail)
Exemple #25
0
    def test_from_xml_wo_detail(self):
        from lxml.etree import Element
        from lxml.etree import SubElement
        import spyne.const.xml_ns
        ns_soap_env = spyne.const.xml_ns.soap_env

        element = Element('{%s}Fault' % ns_soap_env)
        fcode = SubElement(element, 'faultcode')
        fcode.text = 'senv:other'
        fstr = SubElement(element, 'faultstring')
        fstr.text = 'Testing'
        actor = SubElement(element, 'faultactor')
        actor.text = 'phreddy'

        fault = XmlDocument().from_element(Fault, element)

        self.assertEqual(fault.faultcode, 'senv:other')
        self.assertEqual(fault.faultstring, 'Testing')
        self.assertEqual(fault.faultactor, 'phreddy')
        self.assertEqual(fault.detail, None)
Exemple #26
0
    def test_from_xml_wo_detail(self):
        from lxml.etree import Element
        from lxml.etree import SubElement
        from spyne.const.xml import PREFMAP, SOAP11_ENV, NS_SOAP11_ENV

        soap_env = PREFMAP[NS_SOAP11_ENV]
        element = Element(SOAP11_ENV('Fault'))

        fcode = SubElement(element, 'faultcode')
        fcode.text = '%s:other' % soap_env
        fstr = SubElement(element, 'faultstring')
        fstr.text = 'Testing'
        actor = SubElement(element, 'faultactor')
        actor.text = 'phreddy'

        fault = XmlDocument().from_element(None, Fault, element)

        self.assertEqual(fault.faultcode, '%s:other' % soap_env)
        self.assertEqual(fault.faultstring, 'Testing')
        self.assertEqual(fault.faultactor, 'phreddy')
        self.assertEqual(fault.detail, None)
Exemple #27
0
def get_xml_as_object_polymorphic(elt, cls):
    """Returns a native :class:`spyne.model.complex.ComplexModel` child from an
    ElementTree representation of the same class.

    :param elt: The xml document to be deserialized.
    :param cls: The class the xml document represents.
    """

    tns = cls.get_namespace()
    if tns is None:
        raise ValueError("Please set a namespace for %r" % (cls, ))

    class _DummyService(ServiceBase):
        @srpc(cls)
        def f(_):
            pass

    app = Application([_DummyService],
                      tns=tns,
                      in_protocol=XmlDocument(polymorphic=True))

    unregister_application(app)

    return app.in_protocol.from_element(FakeContext(app=app), cls, elt)
Exemple #28
0
def getSpyneApplications(wof_obj_1_0, wof_obj_1_1, templates=None):

    # wof_obj_1_0 = wof_1_0.WOF(dao, config_file)
    # wof_obj_1_1 = wof_1_1.WOF_1_1(dao,config_file)

    sensorNetwork = wof_obj_1_0.urlpath.replace('/', '').lower()

    soap_app_1_0 = Application(
        [wml10(wof_obj_1_0, Unicode, _SERVICE_PARAMS["s_type"])],
        tns=_SERVICE_PARAMS["wml10_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml10_soap_name"],
        in_protocol=wofSoap11(validator='lxml'),
        out_protocol=Soap11(),
    )

    rest_app_1_0 = Application(
        [wml10(wof_obj_1_0, AnyXml, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml10_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml10_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        out_protocol=XmlDocument(),
    )

    soap_app_1_1 = Application(
        [wml11(wof_obj_1_1, Unicode, _SERVICE_PARAMS["s_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork+'_svc_' + _SERVICE_PARAMS["wml11_soap_name"],
        in_protocol=wofSoap11(validator='lxml'),
        out_protocol=Soap11(),
    )

    rest_app_1_1 = Application(
        [wml11(wof_obj_1_1, AnyXml, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        out_protocol=XmlDocument(),
    )
    # need to update template to 1_1 object.
    # <gml:Definition gml:id="methodCode-{{ method_result.MethodID  }}">
    #   File "\lib\site-packages\jinja2\environment.py", line 408, in getattr
    #     return getattr(obj, attribute)
    # UndefinedError: 'method_result' is undefined
    rest_app_2 = Application(
        [wml2(wof_obj_1_0, Unicode, _SERVICE_PARAMS["r_type"])],
        tns=_SERVICE_PARAMS["wml11_tns"],
        name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"],
        in_protocol=HttpRpc(validator='soft'),
        # out_protocol=XmlDocument(),
        out_protocol=HttpRpc(mime_type='text/xml'),

    )

    rest_wsgi_wrapper_1_0 = WsgiApplication(rest_app_1_0)
    soap_wsgi_wrapper_1_0 = WsgiApplication(soap_app_1_0)
    rest_wsgi_wrapper_1_1 = WsgiApplication(rest_app_1_1)
    soap_wsgi_wrapper_1_1 = WsgiApplication(soap_app_1_1)
    rest_wsgi_wrapper_2_0 = WsgiApplication(rest_app_2)

    spyneApps = {
        '/' + sensorNetwork+'/rest/1_0': rest_wsgi_wrapper_1_0,
        '/' + sensorNetwork+'/rest/1_1': rest_wsgi_wrapper_1_1,
        '/' + sensorNetwork+'/soap/cuahsi_1_0': soap_wsgi_wrapper_1_0,
        '/' + sensorNetwork+'/soap/cuahsi_1_1': soap_wsgi_wrapper_1_1,
        '/' + sensorNetwork+'/rest/2': rest_wsgi_wrapper_2_0,
    }

    templatesPath = None
    if templates is None:
        if wof_obj_1_1._config is not None:
            templatesPath = os.path.abspath(wof_obj_1_1._config.TEMPLATES)
    else:
        templatesPath = os.path.abspath(templates)

    if templatesPath:
        if not os.path.exists(templatesPath):
            logging.info('Templates path: {} NOT exists {}'.format(
                templatesPath,
                os.path.exists(templatesPath))
            )
            templatesPath = _TEMPLATES
            logging.info('default temnplate path: %s' % templatesPath)
        # needs to be service_baseURL. in config wof_obj_1_0.service_wsdl
        wsdl10 = WofWSDL_1_0(
            soap_wsgi_wrapper_1_0.doc.wsdl11.interface,
            templates=templatesPath,
            network=sensorNetwork,
            version=version
        )

        # soap_wsgi_wrapper_1_0._wsdl = wsdl10.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow')  # noqa
        soap_wsgi_wrapper_1_0.event_manager.add_listener(
            'wsdl',
            wsdl10.on_get_wsdl_1_0_
        )
        # path: /{sensorNetwork}/soap/wateroneflow_1_1/.wsdl returns the WSDL.
        wsdl11 = WofWSDL_1_1(
            soap_wsgi_wrapper_1_1.doc.wsdl11.interface,
            templates=templatesPath,
            network=sensorNetwork,
            version=version
        )
        # soap_wsgi_wrapper_1_1._wsdl = wsdl11.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow_1_1',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow')  # noqa
        soap_wsgi_wrapper_1_1.event_manager.add_listener(
            'wsdl',
            wsdl11.on_get_wsdl_1_1_
        )

    return spyneApps
Exemple #29
0
from spyne.model import Null, XmlData, XmlAttribute, Array, ComplexModelBase, \
    ComplexModelMeta
from spyne.model.complex import XmlModifier

from spyne.protocol.xml import XmlDocument

from spyne.interface.xml_schema.defn import TYPE_MAP
from spyne.interface.xml_schema.defn import SchemaBase
from spyne.interface.xml_schema.defn import XmlSchema10

from spyne.util.color import R, G, B, MAG, YEL

PARSER = etree.XMLParser(remove_comments=True)

_prot = XmlDocument()


class _Schema(object):
    def __init__(self):
        self.types = {}
        self.elements = {}
        self.imports = set()


# FIXME: Needs to emit delayed assignment of recursive structures instead of
# lousy ellipses.
@memoize
def Thier_repr(with_ns=False):
    """Template for ``hier_repr``, a ``repr`` variant that shows spyne
    ``ComplexModel``s in a hierarchical format.
Exemple #30
0
 def test_xml_encoding(self):
     ctx = FakeContext(out_document=E.rain(u"yağmur"))
     XmlDocument(encoding='iso-8859-9').create_out_string(ctx)
     s = b''.join(ctx.out_string)
     assert u"ğ".encode('iso-8859-9') in s
Exemple #31
0
    def __init__(self, app=None, validator=None, wrapped=True,
                                xml_declaration=True, cleanup_namespaces=True):
        XmlDocument.__init__(self, app, validator, xml_declaration,
                                                             cleanup_namespaces)

        self.__wrapped = wrapped
Exemple #32
0
    @srpc(String, Integer, _returns=Iterable(String))
    def say_hello(name, times):
        '''
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''

        for i in range(times):
            yield 'Hello, %s' % name


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

    logging.basicConfig(level=logging.DEBUG)

    application = Application([HelloWorldService],
                              'spyne.examples.hello.http',
                              in_protocol=HttpRpc(),
                              out_protocol=XmlDocument())

    server = make_server('127.0.0.1', 7789, WsgiApplication(application))

    logging.info("listening to http://127.0.0.1:7789")
    logging.info("wsdl is at: http://localhost:7789/?wsdl")

    server.serve_forever()
Exemple #33
0
    def test_multiple_attribute_of_multiple_rpc(self):
        """
        Tests the following:

        1. Support for multiple attributes on a single element.
        2. Correctness of attribute definition -- extension applied to correct 'attribute_of' element.
        3. Another class/rpc with same element/attribute name works correctly.
        """


        class CMA(ComplexModel):
            a = Unicode
            ab = XmlAttribute(Unicode, attribute_of="a")
            ac = XmlAttribute(Unicode, attribute_of="a")
            ad = XmlAttribute(Integer, attribute_of="a")

            b = Integer
            bb = XmlAttribute(Unicode, attribute_of="b")

        class CMB(ComplexModel):
            b = Integer
            bb = XmlAttribute(Unicode, attribute_of="b")



        class SomeService(ServiceBase):
            @srpc(CMA, _returns=CMA)
            def some_call(cma):
                assert cma.a == 'a'
                assert cma.ab == 'b'
                assert cma.ac == 'c'
                assert cma.ad == 5
                assert cma.b == 9
                assert cma.bb == "attrib bb"
                return cma

            @srpc(CMB, _returns=CMB)
            def another_call(cmb):
                assert cmb.b == 9
                assert cmb.bb == 'attrib bb'
                return cmb

        app = Application([SomeService], "tns", name="test_multiple_attribute_of",
                        in_protocol=XmlDocument(), out_protocol=XmlDocument())
        server = ServerBase(app)

        # test some_call(CMA)

        initial_ctx = MethodContext(server)
        initial_ctx.in_string = [
            '<some_call xmlns="tns">'
                '<cma>'
                    '<a ab="b" ac="c" ad="5">a</a>'
                    '<b bb="attrib bb">9</b>'
                '</cma>'
            '</some_call>'
        ]

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

        ret = ''.join(ctx.out_string)
        print(ret)
        ret = etree.fromstring(ret)
        ret = ret.xpath('//s0:a', namespaces=app.interface.nsmap)[0]

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

        assert ret.text == "a"
        assert ret.attrib['ab'] == "b"
        assert ret.attrib['ac'] == "c"
        assert int(ret.attrib['ad']) == 5

        ret = ret.xpath('//s0:b', namespaces=app.interface.nsmap)[0]
        print(etree.tostring(ret, pretty_print=True))

        assert ret.text == "9"
        assert ret.attrib['bb'] == "attrib bb"

        # test another_call(CMB)

        initial_ctx = MethodContext(server)
        initial_ctx.in_string = [
            '<another_call xmlns="tns">'
                '<cmb>'
                    '<b bb="attrib bb">9</b>'
                '</cmb>'
            '</another_call>'
        ]

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

        ret = ''.join(ctx.out_string)
        print(ret)
        ret = etree.fromstring(ret)
        ret = ret.xpath('//s0:b', namespaces=app.interface.nsmap)[0]

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

        assert ret.text == "9"
        assert ret.attrib['bb'] == "attrib bb"
Exemple #34
0
    @srpc(Integer)
    def delete_user(userid):
        global user_database

        if not (userid in user_database):
            raise ResourceNotFoundError(userid)

        del user_database[userid]

    @srpc(_returns=Array(User))
    def list_users():
        global user_database

        return user_database.values()

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

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

    application = Application([UserManager], 'spyne.examples.complex',
                interface=Wsdl11(), in_protocol=HttpRpc(), out_protocol=XmlDocument())

    server = make_server('127.0.0.1', 7789, WsgiApplication(application))

    logging.info("listening to http://127.0.0.1:7789")
    logging.info("wsdl is at: http://localhost:7789/?wsdl")

    server.serve_forever()
Exemple #35
0
        m.resolve_namespace(m, default_namespace)
        interface.add_class(m)

    schema = XmlSchema(interface)
    schema.build_validation_schema()

    return schema.validation_schema


def _dig(par):
    for elt in par:
        elt.tag = elt.tag.split('}')[-1]
        _dig(elt)


_xml_object = XmlDocument()


def get_object_as_xml(inst, cls=None, root_tag_name=None, no_namespace=False):
    """Returns an ElementTree representation of a
    :class:`spyne.model.complex.ComplexModel` subclass.

    :param inst: The instance of the class to be serialized.
    :param cls: The class to be serialized. Optional.
    :param root_tag_name: The root tag string to use. Defaults to the output of
        ``value.__class__.get_type_name_ns()``.
    :param no_namespace: When true, namespace information is discarded.
    """

    if cls is None:
        cls = inst.__class__
Exemple #36
0
    def test_boolean(self):
        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, True, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.text)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, 0, b, ns_test)
        b = b[0]
        self.assertEquals('false', b.text)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, 1, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.text)

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, True)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, False, b, ns_test)
        b = b[0]
        self.assertEquals('false', b.text)

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, False)

        b = etree.Element('test')
        XmlDocument().to_parent(None, Boolean, None, b, ns_test)
        b = b[0]
        self.assertEquals('true', b.get(ns.XSI('nil')))

        b = XmlDocument().from_element(None, Boolean, b)
        self.assertEquals(b, None)
Exemple #37
0
def main():
    global protocols

    rest = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=HttpRpc())

    xml = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=XmlDocument())

    soap = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=Soap11())

    html = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=HtmlMicroFormat())

    png = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=PngClock())

    svg = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=SvgClock())

    json = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=JsonDocument())

    jsoni = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=JsonDocument(
                                                         ignore_wrappers=True))

    jsonl = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=JsonDocument(complex_as=list))

    jsonil = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=JsonDocument(
                                        ignore_wrappers=True, complex_as=list))

    msgpack_doc = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=MessagePackDocument())

    msgpack_rpc = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=MessagePackRpc())

    yaml = Application([MultiProtService], tns=tns,
            in_protocol=HttpRpc(), out_protocol=YamlDocument())

    dyn = Application([DynProtService], tns=tns,
            in_protocol=HttpRpc(validator='soft'), out_protocol=HttpRpc())

    DynProtService.protocols = {
        'json':  Tsetprot(JsonDocument(dyn)),
        'xml':  Tsetprot(XmlDocument(dyn)),
        'yaml':  Tsetprot(YamlDocument(dyn)),
        'soap':  Tsetprot(Soap11(dyn)),
        'html':  Tsetprot(HtmlMicroFormat(dyn)),
        'png':  Tsetprot(PngClock(dyn)),
        'svg':  Tsetprot(SvgClock(dyn)),
        'msgpack':  Tsetprot(MessagePackDocument(dyn)),
    }

    root = WsgiMounter({
        'rest': rest,
        'xml': xml,
        'soap': soap,
        'html': html,
        'png': png,
        'svg': svg,
        'json': json,
        'jsoni': jsoni,
        'jsonl': jsonl,
        'jsonil': jsonil,
        'mpd': msgpack_doc,
        'mprpc': msgpack_rpc,
        'yaml': yaml,
        'dyn': dyn,
    })

    from wsgiref.simple_server import make_server
    server = make_server(host, port, root)

    logging.basicConfig(level=logging.DEBUG)
    logging.info("listening to http://%s:%d" % (host, port))
    logging.info("navigate to e.g. http://%s:%d/json2/get_utc_time" %
                                                                  (host, port))
    logging.info("             or: http://%s:%d/xml/get_utc_time" %
                                                                  (host, port))

    return server.serve_forever()