def test_inherited_attribute(self): class DeviceEntity(ComplexModel): token = XmlAttribute(Unicode, use='required') class DigitalInput(DeviceEntity): IdleState = XmlAttribute(Unicode) class SomeService(Service): @rpc(_returns=DigitalInput, _body_style='bare') def GetDigitalInput(ctx): return DigitalInput() Application([SomeService], 'some_tns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
def main(): logging.basicConfig(level=logging.WARNING) spyne_app = SpyneApplication( [HelloWorldService], tns="aiohttp_spyne.examples.hello", in_protocol=Soap11(validator="lxml"), out_protocol=Soap11(), ) handler = AIOSpyne(spyne_app, threads=20) app = web.Application() app.router.add_get("/say_hello/{tail:.*}", handler.get) app.router.add_post("/say_hello/{tail:.*}", handler.post) web.run_app(app, port=8080)
def test_to_parent_nested(self): m = ComplexModel.produce( namespace=None, type_name='myMessage', members={'p':Person} ) m.resolve_namespace(m, "m") p = Person() p.name = 'steve-o' p.age = 2 p.addresses = [] for i in range(0, 100): a = Address() a.street = '123 happy way' a.zip = i a.laditude = '45.22' a.longitude = '444.234' p.addresses.append(a) m_inst = m(p=p) element=etree.Element('test') Soap11().to_parent(None, m, m_inst, element, m.get_namespace()) element=element[0] self.assertEquals('{%s}myMessage' % m.get_namespace(), element.tag) addresses = element[0].find('{%s}addresses' % Person.get_namespace()) self.assertEquals(100, len(addresses)) self.assertEquals('0', addresses[0].find('{%s}zip' % Address.get_namespace()).text)
def assert_soap_ok(self, suffix, _operation_name=None, _in_message_name=None): """helper to test soap requests""" # setup app = self.get_app(Soap11(validator='lxml'), suffix, _operation_name, _in_message_name) function_name, operation_name, request_name = self.get_function_names( suffix, _operation_name, _in_message_name) soap_input_body = """ <SOAP-ENV:Envelope xmlns:ns0="spyne.examples.echo" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <ns1:Body> <ns0:{0}> <ns0:string>test</ns0:string> <ns0:times>2</ns0:times> </ns0:{0}> </ns1:Body> </SOAP-ENV:Envelope>""".format(request_name) # check wsdl wsdl = app.get('/?wsdl') self.assertEqual(wsdl.status_int, 200, wsdl) self.assertTrue(request_name in wsdl, '{0} not found in wsdl'.format(request_name)) soap_strings = [ '<wsdl:operation name="{0}"'.format(operation_name), '<soap:operation soapAction="{0}"'.format(operation_name), '<wsdl:input name="{0}">'.format(request_name), '<xs:element name="{0}"'.format(request_name), '<xs:complexType name="{0}">'.format(request_name), ] for soap_string in soap_strings: self.assertTrue(soap_string in wsdl, '{0} not in {1}'.format(soap_string, wsdl)) if request_name != operation_name: wrong_string = '<wsdl:operation name="{0}"'.format(request_name) self.assertFalse(wrong_string in wsdl, '{0} in {1}'.format(wrong_string, wsdl)) output_name = '<wsdl:output name="{0}Response"'.format( self.default_function_name) self.assertTrue( output_name in wsdl, 'REQUEST_SUFFIX or _in_message_name changed the ' 'output name, it should be: {0}'.format(output_name)) # check soap operation succeeded resp = app.post('/', soap_input_body, content_type='applicaion/xml; charset=utf8') self.assert_response_ok(resp)
def get_app(self, in_protocol, suffix, _operation_name=None, _in_message_name=None): '''setup testapp dependent on suffix and _in_message_name''' import spyne.const spyne.const.REQUEST_SUFFIX = suffix class EchoService(ServiceBase): srpc_kparams = {'_returns': Iterable(Unicode)} if _in_message_name: srpc_kparams['_in_message_name'] = _in_message_name if _operation_name: srpc_kparams['_operation_name'] = _operation_name @srpc(Unicode, Integer, **srpc_kparams) def echo(string, times): for i in range(times): yield 'Echo, %s' % string application = Application([EchoService], tns='spyne.examples.echo', in_protocol=in_protocol, out_protocol=Soap11()) app = WsgiApplication(application) testapp = TestApp(app) # so that it doesn't interfere with other tests. spyne.const.REQUEST_SUFFIX = '' return testapp
def test_date_with_tzoffset(self): for iso_d in ('2013-04-05', '2013-04-05+02:00', '2013-04-05-02:00', '2013-04-05Z'): d = Soap11().from_unicode(Date, iso_d) assert isinstance(d, datetime.date) == True assert d.year == 2013 assert d.month == 4 assert d.day == 5
def conn(): print("spawning server") application = Application([XmlaProviderService], 'urn:schemas-microsoft-com:xml-analysis', in_protocol=Soap11(validator='soft'), out_protocol=Soap11(validator='soft')) wsgi_application = WsgiApplication(application) server = WSGIServer(application=wsgi_application, host=HOST, port=PORT) server.start() provider = xmla.XMLAProvider() conn = provider.connect(location=server.url) yield conn print("stopping server") server.stop()
class soapDatabase(spyne.Service): __service_url_path__ = '/soap/database' __in_protocol__ = Soap11(validator='lxml') __out_protocol__ = Soap11() @spyne.srpc(String, _returns=String) def select(rollno): dbase = MySQLdb.connect('localhost', 'root', 'harshahj97', 'example') cur = dbase.cursor() query = "select * from student where rollno='" + rollno + "'" try: cur.execute(query) ans = cur.fetchall() for row in ans: return ' '.join(row[1:]) except e: pass
class BgSoapService(spyne.Service): __service_url_path__ = '/soap/bgservice' __in_protocol__ = Soap11(validator='lxml') __out_protocol__ = Soap11() @spyne.srpc(Unicode, Unicode, Unicode, Integer, _returns=Iterable(Unicode)) def reflection(title, address, application, id): yield title yield address yield application yield str(id) @spyne.srpc(Unicode, Unicode, Unicode, _returns=Unicode) def tran(title, address, application): static_id = randint(0, 100) return str(static_id)
def create_in_document(self, ctx, charset=None): if isinstance(ctx.transport, HttpTransportContext): http_verb = ctx.transport.get_request_method() if http_verb == "OPTIONS": ctx.transport.resp_headers['allow'] = "POST, OPTIONS" ctx.transport.respond(HTTP_200) raise Fault("") return Soap11.create_in_document(self, ctx, charset)
def soap_get(flask_app): Sget = Application( [DictWage], tns=flask_app.config.get('NAMESPACE'), name='DictWage', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) def _flask_config_context(ctx): ctx.udc = UserDefinedContext(flask_app) Sget.event_manager.add_listener( 'method_call', _flask_config_context ) return Sget
def test_implicit_class_conflict(self): class someCallResponse(ComplexModel): __namespace__ = 'tns' s = String class SomeService(Service): @rpc(someCallResponse, _returns=String) def someCall(ctx, x): return ['abc', 'def'] try: Application([SomeService], 'tns', in_protocol=Soap11(), out_protocol=Soap11(cleanup_namespaces=True)) except ValueError as e: print(e) else: raise Exception("must fail.")
def main(): # You can use any Wsgi server. Here, we chose # Python's built-in wsgi server but you're not # supposed to use it in production. application = Application( [WebAPIService], tns="spyne.examples.hello", # tns="tns", in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_app = WsgiApplication(application) host = '0.0.0.0' port = 5558 print "http://%s:%d" % (host, port) server = make_server(host, port, wsgi_app) server.serve_forever()
class SomeSoapService(spyne.Service): __service_url_path__ = '/soap/someservice' __in_protocol__ = Soap11(validator='lxml') __out_protocol__ = Soap11() @spyne.srpc(Unicode, Integer, _returns=Iterable(Unicode)) def distance(self, longitudeA, latitudeA, longitudeB, latitudeB): longitudeA = math.radians(longitudeA) latitudeA = math.radians(latitudeA) longitudeB = math.radians(longitudeB) latitudeB = math.radians(latitudeB) dlongitude = longitudeB - longitudeA radian = math.acos( math.sin(latitudeA) * math.sin(latitudeB) + math.cos(latitudeA) * math.cos(latitudeB) * math.cos(dlongitude)) result = radian * 6378137 return result
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'
def test_customized_simple_type_in_xml_attribute(self): class Product(ComplexModel): __namespace__ = 'some_ns' id = XmlAttribute(Uuid) edition = Unicode class SomeService(ServiceBase): @rpc(Product, _returns=Product) def echo_product(ctx, product): logging.info('edition_id: %r', product.edition_id) return product Application([SomeService], tns='some_ns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() )
def setUp(self): self.app = Application([TestService], 'tns', in_protocol=Soap11(), out_protocol=Soap11()) 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)
class AlbumsSoapService(spyne.Service): __soap_target_namespace__ = 'MyNS' __soap_server_address__ = '/soap/albums' __service_url_path__ = '/soap/albums' __in_protocol__ = Soap11(validator='lxml') __out_protocol__ = Soap11() @spyne.srpc(Unicode, Integer, _returns=Iterable(Album)) def hello(str, cnt): for i in range(cnt): yield str @spyne.srpc(_returns=Array(Album)) def getAlbumSoap(): a = [] for album in albums: a.append(Album(ID=album["ID"], Albums=album["Album"], Artist=album["Artist"], Genre=album["Genre"], Producer=album["Producer"], MovieID=album["MovieID"])) return a
def getWsgiApp(type): if type == 'case': service = TextService elif type == 'ip': service = ResolveIP elif type == 'loan': service = VinniesLoanService else: raise Exception('Invalid service type.') app = Application( [service], 'magu.dev', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) return WsgiApplication(app)
def test_b64_attribute(self): class PacketAttribute(ComplexModel): __namespace__ = 'myns' Data = XmlAttribute(ByteArray, use='required') test_string = 'yo test data' b64string = b64encode(test_string) gg = PacketAttribute(Data=test_string) element = etree.Element('test') Soap11().to_parent(None, PacketAttribute, gg, element, gg.get_namespace()) element = element[0] #print etree.tostring(element, pretty_print=True) self.assertEquals(element.attrib['Data'], b64string) s1 = Soap11().from_element(None, PacketAttribute, element) assert s1.Data[0] == test_string
def __init__(self, server_address, url, api, is_ssl): WSGIServer.__init__(self, server_address, ApiHandler) self.is_ssl = is_ssl if self.is_ssl: self.base_environ["HTTPS"] = "yes" app = ApiApplication( Application([SubregCzService], 'http://subreg.cz/wsdl', 'SubregCzService', in_protocol=Soap11(), out_protocol=Soap11(), config={"api": api})) self.set_app(app) app.doc.wsdl11.build_interface_document(url)
def test_single_method(self): try: Application([MultipleMethods1,MultipleMethods2], 'tns', in_protocol=Soap11(), out_protocol=Soap11()) except ValueError: pass else: raise Exception('must fail.')
def create_app(flask_app): application = Application( [WhoisServiceSOAP], 'whoisinfo.service', in_protocol=Soap11(), out_protocol=Soap11(), ) def _flask_config_context(ctx): ctx.udc = UserDefinedContext(flask_app.config) application.event_manager.add_listener('method_call', _flask_config_context) #output_wsdl(application) # to output wsdl file lul #wsdl output is found at 'http://localhost:5000/soap/?wsdl' return application
def pyramid_soap11_application(services, tns='spyne.simple.soap', validator=None, name=None): """Wraps `services` argument inside a PyramidApplication that uses Wsdl 1.1 as interface document and Soap 1.1 and both input and output protocols. """ from spyne.protocol.soap import Soap11 from spyne.server.pyramid import PyramidApplication application = Application(services, tns, name=name, in_protocol=Soap11(validator=validator), out_protocol=Soap11()) return PyramidApplication(application)
def wsgi_soap11_application(services, tns='spyne.simple.soap', validator=None, name=None): """Wraps `services` argument inside a WsgiApplication that uses Soap 1.1 for both input and output protocols. """ from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication application = Application(services, tns, name=name, in_protocol=Soap11(validator=validator), out_protocol=Soap11()) return WsgiApplication(application)
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
def test_simple_type_explicit_customization(self): class Header(ComplexModel): test = Boolean(min_occurs=0, nillable=False) pw = Unicode.customize(min_occurs=0, nillable=False, min_len=6) class Params(ComplexModel): sendHeader = Header.customize(nillable=False, min_occurs=1) class DummyService(ServiceBase): @rpc(Params, _returns=Unicode) def loadServices(ctx, serviceParams): return '42' Application([DummyService], tns='dummy', name='DummyService', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
def test_2(): from upnpy_spyne.services.templates.switchpower import SwitchPower # log.startLogging(sys.stdout) client = Client( 'http://192.168.0.60:8000', Application([SwitchPower], SwitchPower.tns, in_protocol=Soap11(), out_protocol=Soap11())) client.set_options( out_header={'Content-Type': ['text/xml;charset="utf-8"'], 'Soapaction': [SwitchPower.tns]}) d = client.service.GetStatus() d.addCallback(log.debug) onoff = False for i in range(6): reactor.callLater( # @UndefinedVariable i, client.service.SetTarget, not onoff) onoff = not onoff
def test_b64_non_attribute(self): class PacketNonAttribute(ComplexModel): __namespace__ = 'myns' Data = ByteArray test_string = b'yo test data' b64string = b64encode(test_string) gg = PacketNonAttribute(Data=[test_string]) element = etree.Element('test') Soap11().to_parent(None, PacketNonAttribute, gg, element, gg.get_namespace()) element = element[0] #print etree.tostring(element, pretty_print=True) data = element.find('{%s}Data' % gg.get_namespace()).text self.assertEquals(data, b64string.decode('ascii')) s1 = Soap11().from_element(None, PacketNonAttribute, element) assert s1.Data[0] == test_string
def spyne_app_process(): class TestService(ServiceBase): @rpc(Unicode, _returns=Unicode) def ping(self, data): return data spyne_app = Application( [TestService], tns="aiohttp_spyne.tests.test", in_protocol=Soap11(validator="lxml"), out_protocol=Soap11(), ) handler = AIOSpyne(spyne_app) app = web.Application(client_max_size=1024**2 * 2) app.router.add_get("/{tail:.*}", handler.get) app.router.add_post("/{tail:.*}", handler.post) web.run_app(app, host="0.0.0.0", port=PORT)