def get_object_as_xml_polymorphic(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__ if no_namespace: app = Application([ServiceBase], tns="", out_protocol=XmlDocument(polymorphic=True)) else: tns = cls.get_namespace() if tns is None: raise ValueError( "Either set a namespace for %r or pass no_namespace=True" % (cls, )) class _DummyService(ServiceBase): @srpc(cls) def f(_): pass app = Application([_DummyService], tns=tns, out_protocol=XmlDocument(polymorphic=True)) unregister_application(app) parent = etree.Element("parent", nsmap=app.interface.nsmap) app.out_protocol.to_parent(None, cls, inst, parent, cls.get_namespace(), root_tag_name) if no_namespace: _dig(parent) etree.cleanup_namespaces(parent) return parent[0]
def _test_type(cls, inst): from spyne.util import appreg appreg._applications.clear() class SomeService(ServiceBase): @rpc(_returns=cls, _body_style='bare') def some_call(ctx): return inst prot = HtmlForm(cloth=T_TEST) app = Application([SomeService], 'some_ns', out_protocol=prot) null = NullServer(app, ostr=True) ret = ''.join(null.service.some_call()) try: elt = html.fromstring(ret) except: print(ret) raise show(elt, stdout=False) elt = elt.xpath('//*[@spyne]')[0][ 0] # get the form tag inside the body tag elt = strip_ns(elt) # get rid of namespaces to simplify xpaths in tests print(etree.tostring(elt, pretty_print=True)) return elt
def test_roundtrip_deferred(self): from twisted.internet import reactor from twisted.internet.task import deferLater v = "yaaay!" p_ctx = [] class SomeService(ServiceBase): @rpc(Unicode, _returns=Unicode) def yay(ctx, u): def _cb(): return u p_ctx.append(ctx) return deferLater(reactor, 0.1, _cb) app = Application([SomeService], 'tns', in_protocol=MessagePackDocument(), out_protocol=MessagePackDocument()) prot = self.gen_prot(app) request = msgpack.packb({'yay': [v]}) def _ccb(_): val = prot.transport.value() print repr(val) val = msgpack.unpackb(val) print repr(val) self.assertEquals(val, [0, msgpack.packb(v)]) prot.dataReceived(msgpack.packb([1, request])) return p_ctx[0].out_object[0].addCallback(_ccb)
def test_self_referential_array_workaround(self): from spyne.util.dictdoc import get_object_as_dict class Category(ComplexModel): id = Integer(min_occurs=1, max_occurs=1, nillable=False) Category._type_info['children'] = Array(Category) parent = Category() parent.children = [Category(id=0), Category(id=1)] d = get_object_as_dict(parent, Category) pprint(d) assert d['children'][0]['id'] == 0 assert d['children'][1]['id'] == 1 class SoapService(ServiceBase): @rpc(_returns=Category) def view_categories(ctx): pass Application([SoapService], 'service.soap', in_protocol=ProtocolBase(), out_protocol=ProtocolBase())
def get_application(): application = Application([CampaignCrudService, ModuleCrudService], tns='pvtranslator', in_protocol=Soap11(), out_protocol=Soap11()) return application
def test_binary_encodings(self): class Product(ComplexModel): __namespace__ = 'some_ns' hex = ByteArray(encoding='hex') base64_1 = ByteArray(encoding='base64') base64_2 = ByteArray class SomeService(ServiceBase): @rpc(Product, _returns=Product) def echo_product(ctx, product): logging.info('edition_id: %r', product.edition_id) return product app = Application([SomeService], tns='some_ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) _ns = {'xs': NS_XSD} pref_xs = ns.PREFMAP[NS_XSD] xs = XmlSchema(app.interface) xs.build_interface_document() elt = xs.get_interface_document()['tns'].xpath( '//xs:complexType[@name="Product"]', namespaces=_ns)[0] assert elt.xpath('//xs:element[@name="base64_1"]/@type', namespaces=_ns)[0] == '%s:base64Binary' % pref_xs assert elt.xpath('//xs:element[@name="base64_2"]/@type', namespaces=_ns)[0] == '%s:base64Binary' % pref_xs assert elt.xpath('//xs:element[@name="hex"]/@type', namespaces=_ns)[0] == '%s:hexBinary' % pref_xs
def test_receiveItemBarCode(): obj = mod.TXml( Header=mod.Header( Message_Type='mt', Company_ID='ci', Version='v', Source='s', Destination='d', Action_Type='read', Sequence_Number=1, Batch_ID='bi', Reference_ID='ri', Msg_Locale='ml', Msg_Time_Zone='mtz', Internal_Date_Time_Stamp='idts', ), Message=mod.Message(ItemBarCodeList=[ mod.ItemBarCode(IsPrimary='ip', ItemCode='ic', Barcode='b', Quantity='q', ActionType='at', BarcodeType='bt', Extensions=[ mod.Extensions( FieldCode='fc', FieldCodeDesc='fcd', FieldValue='fv', ), mod.Extensions( FieldCode='fc', FieldCodeDesc='fcd', FieldValue='fv', ), ]), mod.ItemBarCode(IsPrimary='ip', ItemCode='ic', Barcode='b', Quantity='q', ActionType='at', BarcodeType='bt', Extensions=[ mod.Extensions( FieldCode='fc', FieldCodeDesc='fcd', FieldValue='fv', ), mod.Extensions( FieldCode='fc', FieldCodeDesc='fcd', FieldValue='fv', ), ]), ]), ) server = NullServer( Application([rpc.receiveItemBarCodeService], 'some_tns')) # Using ``_body_style='bare'`` seems to cause to always return # ``None``. Hence we can't check the response object. server.service.receiveItemBarCode(obj)
def testGetWsdl(self): """Simple test for serving of WSDL by spyne through pyramid route""" application = PyramidApplication( Application([self.HelloWorldService], tns='spyne.examples.hello', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())) config = Configurator(settings={'debug_all': True}) config.add_route('home', '/') config.add_view(application, route_name='home') wsgi_app = validator(config.make_wsgi_app()) env = { 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'QUERY_STRING': 'wsdl', } setup_testing_defaults(env) request = Request(env) resp = request.get_response(wsgi_app) self.assert_(resp.status.startswith("200 ")) node = etree.XML(resp.body) # will throw exception if non well formed
def _build_xml_data_test_schema(self, custom_root): tns = 'kickass.ns' class ProductEdition(ComplexModel): __namespace__ = tns id = XmlAttribute(Uuid) if custom_root: name = XmlData(Uuid) else: name = XmlData(Unicode) class Product(ComplexModel): __namespace__ = tns id = XmlAttribute(Uuid) edition = ProductEdition class ExampleService(ServiceBase): @rpc(Product, _returns=Product) def say_my_uuid(ctx, product): pass app = Application([ExampleService], tns='kickass.ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) schema = XmlSchema(app.interface) schema.build_interface_document() schema.build_validation_schema() doc = schema.get_interface_document()['tns'] print(etree.tostring(doc, pretty_print=True)) return schema
def conn(): engine = sqlalchemy.create_engine("sqlite://") create_insert(engine) executor = MdxEngine(sqla_engine=engine, source_type="db") executor.load_cube(cube_name="main", fact_table_name="facts") discover_request_hanlder = XmlaDiscoverReqHandler(executor) execute_request_hanlder = XmlaExecuteReqHandler(executor) print("spawning server") application = Application( [XmlaProviderService], "urn:schemas-microsoft-com:xml-analysis", in_protocol=Soap11(validator="soft"), out_protocol=Soap11(validator="soft"), config={ "discover_request_hanlder": discover_request_hanlder, "execute_request_hanlder": execute_request_hanlder, }, ) wsgi_application = WsgiApplication(application) server = WSGIServer(application=wsgi_application, host=HOST, port=PORT) server.start() provider = xmla.XMLAProvider() yield provider.connect(location=server.url) print("stopping server") drop_tables(engine) server.stop()
def illustrate_wrappers(self): from spyne.model.complex import ComplexModel, Array from spyne.model.primitive import Unicode class Permission(ComplexModel): _type_info = [ ('application', Unicode), ('feature', Unicode), ] class SomeService(ServiceBase): @srpc(_returns=Array(Permission)) def yay(): return [ Permission(application='app', feature='f1'), Permission(application='app', feature='f2') ] app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument(ignore_wrappers=False)) server = NullServer(app, ostr=True) print ''.join(server.service.yay())
def test_wsdl_validation(self, tmpdir_factory): val = 10 class IntegerService(ServiceBase): @srpc(Integer(ge=20), _returns=Integer) def send(_val): return _val app = Application([IntegerService], 'some_tns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(validator='lxml')) # We have to write the WSDL file using a `WsgiApplication` so # that we get a proper transport URL as it would be # `noconn://null.spyne` with NullServer. wsgi_app = WsgiApplication(app) wsgi_app.doc.wsdl11.build_interface_document('mock://foo') wsdl_file = tmpdir_factory.getbasetemp().join('wsdl') wsdl_file.write(wsgi_app.doc.wsdl11.get_interface_document()) server = NullServer(app, ostr=True) c = Client(str(wsdl_file)) with requests_mock.mock() as m: m.post('mock://foo', content=server.service.send(val)[0]) # This should throw because of `Integer(ge=20)` but doesn't. assert c.service.send(10) == val
def test_namespaced_xml_attribute(self): class Release(ComplexModel): __namespace__ = "http://usefulinc.com/ns/doap#" _type_info = [ ('about', XmlAttribute(Unicode, ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#")), ] class Project(ComplexModel): __namespace__ = "http://usefulinc.com/ns/doap#" _type_info = [ ('about', XmlAttribute(Unicode, ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#")), ('release', Release.customize(max_occurs=float('inf'))), ] class RdfService(ServiceBase): @rpc(Unicode, Unicode, _returns=Project) def some_call(ctx, a, b): pass Application([RdfService], tns='spynepi', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() )
def test_remote_call_error(self): from spyne import mrpc v = 'deger' class SomeComplexModel(ComplexModel): @mrpc(_returns=SelfReference) def put(self, ctx): return v class SomeService(ServiceBase): @rpc(_returns=SomeComplexModel) def get(ctx): return SomeComplexModel() null = NullServer(Application([SomeService], tns='some_tns')) try: null.service.put() except ResourceNotFoundError: pass else: raise Exception( "Must fail with: \"Requested resource " "'{spyne.test.model.test_complex}SomeComplexModel' not found\"" )
def test_wrapped_array_in_wrapped_response(self): from spyne.model.complex import ComplexModel, Array from spyne.model.primitive import Unicode class Permission(ComplexModel): _type_info = [ ('application', Unicode), ('feature', Unicode), ] class SomeService(ServiceBase): @srpc(_returns=Array(Permission)) def yay(): return [ Permission(application='app', feature='f1'), Permission(application='app', feature='f2') ] app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument(ignore_wrappers=False)) server = NullServer(app, ostr=True) retstr = ''.join(server.service.yay()) print(retstr) assert retstr == '{"yayResponse": {"yayResult": [' \ '{"Permission": {"application": "app", "feature": "f1"}}, ' \ '{"Permission": {"application": "app", "feature": "f2"}}]}}'
def test_complex_type_name_clashes(self): class TestComplexModel(ComplexModel): attr1 = String TestComplexModel1 = TestComplexModel class TestComplexModel(ComplexModel): attr2 = String TestComplexModel2 = TestComplexModel class TestService(ServiceBase): @rpc(TestComplexModel1) def test1(ctx, obj): pass @rpc(TestComplexModel2) def test2(ctx, obj): pass try: Application([TestService], 'tns') except Exception as e: print(e) else: raise Exception( "must fail with: " "ValueError: classes " "<class 'spyne.test.model.test_complex.TestComplexModel'> " "and " "<class 'spyne.test.model.test_complex.TestComplexModel'> " "have conflicting names.")
def test_choice_tag(self): class SomeObject(ComplexModel): __namespace__ = "badass_ns" one = Integer(xml_choice_group="numbers") two = Integer(xml_choice_group="numbers") punk = Unicode class KickassService(ServiceBase): @rpc(_returns=SomeObject) def wooo(ctx): return SomeObject() Application([KickassService], tns='kickass.ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) docs = get_schema_documents([SomeObject]) doc = docs['tns'] print(etree.tostring(doc, pretty_print=True)) assert len(doc.xpath('/xs:schema/xs:complexType[@name="SomeObject"]' '/xs:sequence/xs:element[@name="punk"]', namespaces={'xs': NS_XSD})) > 0 assert len(doc.xpath('/xs:schema/xs:complexType[@name="SomeObject"]' '/xs:sequence/xs:choice/xs:element[@name="one"]', namespaces={'xs': NS_XSD})) > 0
def test_customized_class_with_empty_subclass(self): class SummaryStatsOfDouble(ComplexModel): _type_info = [('Min', XmlAttribute(Integer, use='required')), ('Max', XmlAttribute(Integer, use='required')), ('Avg', XmlAttribute(Integer, use='required'))] class SummaryStats(SummaryStatsOfDouble): ''' this is an empty base class ''' class Payload(ComplexModel): _type_info = [('Stat1', SummaryStats.customize(nillable=False)), ('Stat2', SummaryStats), ('Stat3', SummaryStats), ('Dummy', Unicode)] class JackedUpService(ServiceBase): @rpc(_returns=Payload) def GetPayload(ctx): return Payload() Application([JackedUpService], tns='kickass.ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() )
def test_customized_type(self): class SomeClass(ComplexModel): a = XmlAttribute(Integer(ge=4)) class SomeService(ServiceBase): @rpc(SomeClass) def some_call(ctx, some_class): pass app = Application([SomeService], 'some_tns')
def run(self): print("monitor ready :%s" % (self.port)) application = Application([MonitorService], 'monitor', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) self.server = make_server("", int(self.port), wsgi_application) self.server.serve_forever()
def create_server(service, port, protocol): wsgi_app = WsgiApplication( Application([service], 'sa.course', in_protocol=protocol(), out_protocol=protocol())) server = make_server('0.0.0.0', port, wsgi_app) return threading.Thread(target=server.serve_forever)
def create_app(): """Creates an Application object containing the gui app service.""" app = Application([GUIAppService], TNS, in_protocol=Soap11(validator='soft'), out_protocol=Soap11()) return app
def create_app(): """Creates an Application object containing the waiter service.""" app = Application([WaiterPrep], TNS, in_protocol=Soap11(validator='soft'), out_protocol=Soap11()) return app
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].service_class == Service1 assert smm['{%s}some_call' % tns][0].function == Service1.some_call assert smm['{%s}some_other_call' % tns] assert smm['{%s}some_other_call' % tns][0].service_class == Service2 assert smm['{%s}some_other_call' % tns][0].function == Service2.some_other_call
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) return Application(services, 'spyne.examples.twisted.hello', in_protocol=HttpRpc(), out_protocol=HttpRpc())
def test_extensions(self): e = Extensions(FieldCode='fc', FieldCodeDesc='fcd', FieldValue='fv') class ExtensionsService(ServiceBase): @srpc(Extensions, _returns=Extensions) def send(_e): return _e server = NullServer(Application([ExtensionsService], 'some_tns')) assert server.service.send(e) == e
def test_out_kwargs(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument()) assert 'cls' in app.out_protocol.kwargs assert not ('cls' in app.in_protocol.kwargs) app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument(cls='hey')) assert app.out_protocol.kwargs['cls'] == 'hey' assert not ('cls' in app.in_protocol.kwargs)
def test_multilevel_customized_simple_type(self): class ExampleService(ServiceBase): __tns__ = 'http://xml.company.com/ns/example/' @rpc(M(Uuid), _returns=Unicode) def say_my_uuid(ctx, uuid): return 'Your UUID: %s' % uuid Application([ExampleService], tns='kickass.ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
def create_app(flask_app): """Creates SOAP services application and distribute Flask config into user con defined context for each method call. """ application = Application([HelloWorldService], 'spyne.examples.flask', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() # out_protocol=Soap11(), ) return application
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, 'order', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) return application
def __init__(self, *args, **kargs): Application.__init__(self, *args, **kargs) self.status = UpdateStatus()
def __init__(self, *args, **kargs): Application.__init__(self, *args, **kargs) self.pm = ProjectManager("/var/cache/elbe")