def test_nested_flatten_with_multiple_values_2(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM.customize(max_occurs=2) i = Integer s = String class SomeService(ServiceBase): @srpc(CCM, _returns=String) def some_call(ccm): return repr(ccm) app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 'ccm_i=1&ccm_s=s&ccm_c_i=3&ccm_c_s=cs', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) try: server.get_in_object(ctx) except: pass else: raise Exception("Must fail with: Exception: HttpRpc deserializer " "does not support non-primitives with max_occurs > 1")
def __get_ctx(self, mn, qs): server = WsgiApplication(self.application) ctx = WsgiMethodContext(server, { 'QUERY_STRING': qs, 'PATH_INFO': '/%s' % mn, 'REQUEST_METHOD': "GET", }, 'some-content-type') ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) return ctx
def __get_ctx(self, mn, qs): server = WsgiApplication(self.application) ctx = WsgiMethodContext( server, {"QUERY_STRING": qs, "PATH_INFO": "/%s" % mn, "REQUEST_METHOD": "GET", "SERVER_NAME": "localhost"}, "some-content-type", ) ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) return ctx
def test_multiple_return(self): class SomeNotSoComplexModel(ComplexModel): s = String class SomeService(ServiceBase): @srpc(_returns=[Integer, String]) def some_call(): return 1, 's' app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult0">1</div><div class="some_callResult1">s</div></div>'
def test_complex(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM i = Integer s = String class SomeService(ServiceBase): @srpc(CCM, _returns=CCM) def some_call(ccm): return CCM(c=ccm.c, i=ccm.i, s=ccm.s) app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx)
def test_primitive_only(self): class SomeComplexModel(ComplexModel): i = Integer s = String class SomeService(ServiceBase): @srpc(SomeComplexModel, _returns=SomeComplexModel) def some_call(scm): return SomeComplexModel(i=5, s='5x') app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) try: server.get_out_string(ctx) except: pass else: raise Exception("Must fail with: HttpRpc does not support complex " "return types.")
def test_multiple_return(self): class SomeNotSoComplexModel(ComplexModel): s = String class SomeService(ServiceBase): @srpc(_returns=[Integer, String]) def some_call(): return 1, 's' app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'QUERY_STRING': '?s=a', 'REQUEST_METHOD': 'GET', }, 'some-content-type') try: ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) except ValueError: pass else: raise Exception("Must fail with: HttpRpc does not support complex " "return types.")
def _test(services, qs, validator="soft", strict_arrays=False): app = Application( services, "tns", in_protocol=HttpRpc(validator=validator, strict_arrays=strict_arrays), out_protocol=HttpRpc() ) server = WsgiApplication(app) initial_ctx = WsgiMethodContext( server, {"QUERY_STRING": qs, "PATH_INFO": "/some_call", "REQUEST_METHOD": "GET", "SERVER_NAME": "localhost"}, "some-content-type", ) ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) if ctx.in_error is not None: raise ctx.in_error server.get_out_object(ctx) if ctx.out_error is not None: raise ctx.out_error server.get_out_string(ctx) return ctx
def _test(services, qs, validator='soft'): app = Application(services, 'tns', in_protocol=HttpRpc(validator=validator), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': qs, 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': "localhost", }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) if ctx.in_error is not None: raise ctx.in_error server.get_out_object(ctx) if ctx.out_error is not None: raise ctx.out_error server.get_out_string(ctx) return ctx
def test_simple(self): class SomeService(ServiceBase): @srpc(String, _returns=String) def some_call(s): return s app = Application([SomeService], 'tns', in_protocol=HttpRpc(hier_delim='_'), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 's=s', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error is None server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult">s</div></div>'
def __call__(self, request): django_response = HttpResponse() def start_response(status, headers): status, reason = status.split(' ', 1) django_response.status_code = int(status) for header, value in headers: django_response[header] = value environ = request.META.copy() environ['wsgi.input'] = request environ['wsgi.multithread'] = False response = WsgiApplication.__call__(self, environ, start_response) #TODO: можно сказать, что это костыль, без него не работает. #Может быть когда то spyne научится делать это сам, как надо sopa клиенту qiwi data = (u"".join(response))\ .replace('tns:updateBillResult', 'updateBillResult') if self.debug_mode is None: self.debug_mode = bool(settings.DEBUG) if self.debug_mode: logger = logging.getLogger(LOGGER_NAME) logger.debug(u'soap response content: {0}'.format(data)) django_response.content = data if django_response.has_header('Content-Length'): django_response['Content-Length'] = len(data) return django_response
def __call__(self, request): retval = self.HttpResponseObject() def start_response(status, headers): # Status is one of spyne.const.http status, reason = status.split(' ', 1) retval.status_code = int(status) for header, value in headers: retval[header] = value environ = request.META.copy() # FIXME: No idea what these two did. # They were commented out to fix compatibility issues with # Django-1.2.x # See http://github.com/arskom/spyne/issues/222. # If you don't override wsgi.input django and spyne will read # the same buffer twice. If django read whole buffer spyne # would hang waiting for extra request data. Use DjangoServer instead # of monkeypatching wsgi.inpu. #environ['wsgi.input'] = request #environ['wsgi.multithread'] = False response = WsgiApplication.__call__(self, environ, start_response) self.set_response(retval, response) return retval
def __call__(self, request): retval = Response() def start_response(status, headers): status, reason = status.split(' ', 1) retval.status_int = int(status) for header, value in headers: retval.headers[header] = value response = WsgiApplication.__call__(self, request, start_response) retval.body = "".join(response) return retval
def __call__(self, request): pyramid_response = Response() def start_response(status, headers): status, reason = status.split(' ', 1) pyramid_response.status_int = int(status) pyramid_response.headers["Cache-Control"] = "no-cache, must-revalidate" pyramid_response.headers["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT" for header, value in headers: pyramid_response.headers[header] = value response = WsgiApplication.__call__(self, request, start_response) pyramid_response.body = "\n".join(response) return pyramid_response
def __call__(self, request): retval = self.HttpResponse def start_response(status, headers): status, reason = status.split(' ', 1) retval.status_code = int(status) for header, value in headers: retval[header] = value environ = request.META.copy() environ['wsgi.input'] = request environ['wsgi.multithread'] = False response = WsgiApplication.__call__(self, environ, start_response) self.set_response(self, retval, response) return retval
def __call__(self, request): django_response = HttpResponse() def start_response(status, headers): status, reason = status.split(' ', 1) django_response.status_code = int(status) for header, value in headers: django_response[header] = value environ = request.META.copy() environ['wsgi.input'] = request environ['wsgi.multithread'] = False response = WsgiApplication.__call__(self, environ, start_response) django_response.content = "\n".join(response) return django_response
def test_multiple(self): class SomeService(ServiceBase): @srpc(String(max_occurs='unbounded'), _returns=String) def some_call(s): return '\n'.join(s) app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 's=1&s=2', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ctx.out_string == ['1\n2']
def test_nested_flatten(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM i = Integer s = String class SomeService(ServiceBase): @srpc(CCM, _returns=String) def some_call(ccm): return repr(ccm) app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 'ccm_i=1&ccm_s=s&ccm_c_i=3&ccm_c_s=cs', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': "localhost", }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) assert ctx.in_error is None server.get_out_object(ctx) assert ctx.out_error is None server.get_out_string(ctx) print(ctx.out_string) assert ctx.out_string == ["CCM(i=1, c=CM(i=3, s='cs'), s='s')"]
def __call__(self, request): retval = self.HttpResponseObject() def start_response(status, headers): # Status is one of spyne.const.http status, reason = status.split(' ', 1) retval.status_code = int(status) for header, value in headers: retval[header] = value environ = request.META.copy() # FIXME: No idea what these two did. # They were commented out to fix compatibility issues with # Django-1.2.x # See http://github.com/arskom/spyne/issues/222. #environ['wsgi.input'] = request #environ['wsgi.multithread'] = False response = WsgiApplication.__call__(self, environ, start_response) self.set_response(retval, response) return retval
def test_rules(self): _int = 5 _fragment = 'some_fragment' class SomeService(ServiceBase): @srpc(Integer, _returns=Integer, _patterns=[ HttpPattern('/%s/<some_int>'% _fragment)]) def some_call(some_int): assert some_int == _int app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) environ = { 'QUERY_STRING': '', 'PATH_INFO': '/%s/%d' % (_fragment, _int), 'SERVER_PATH':"/", 'SERVER_NAME': "localhost", 'wsgi.url_scheme': 'http', 'SERVER_PORT': '9000', 'REQUEST_METHOD': 'GET', } initial_ctx = WsgiMethodContext(server, environ, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) foo = [] for i in server._http_patterns.iter_rules(): foo.append(i) assert len(foo) == 1 print foo assert ctx.descriptor is not None server.get_in_object(ctx) assert ctx.in_error is None server.get_out_object(ctx) assert ctx.out_error is None
def test_rules(self): _int = 5 _fragment = "some_fragment" class SomeService(ServiceBase): @srpc(Integer, _returns=Integer, _patterns=[HttpPattern("/%s/<some_int>" % _fragment)]) def some_call(some_int): assert some_int == _int app = Application([SomeService], "tns", in_protocol=HttpRpc(), out_protocol=HttpRpc()) server = WsgiApplication(app) environ = { "QUERY_STRING": "", "PATH_INFO": "/%s/%d" % (_fragment, _int), "SERVER_PATH": "/", "SERVER_NAME": "localhost", "wsgi.url_scheme": "http", "SERVER_PORT": "9000", "REQUEST_METHOD": "GET", } initial_ctx = WsgiMethodContext(server, environ, "some-content-type") ctx, = server.generate_contexts(initial_ctx) foo = [] for i in server._http_patterns: foo.append(i) assert len(foo) == 1 print(foo) assert ctx.descriptor is not None server.get_in_object(ctx) assert ctx.in_error is None server.get_out_object(ctx) assert ctx.out_error is None
import json import soap_service from spyne.server.wsgi import WsgiApplication from flask import Flask, make_response, current_app app = Flask(__name__) app.config.from_object('config.Config') app.wsgi_app = WsgiApplication(soap_service.create_app(app)) # @app.route('/hello') # def hello(): # response = make_response(json.dumps({ # 'hello': current_app.config['HELLO'], # })) # response.headers['Content-Type'] = 'application/json' # return response @app.route('/shipping') def shipping(): response = make_response( json.dumps({ 'shipping': current_app.config['SHIPPING'], })) response.headers['Content-Type'] = 'application/json' return response
# -*-coding:utf-8 -*- from werkzeug.wsgi import DispatcherMiddleware from spyne.server.wsgi import WsgiApplication from apps import spyned from apps.flasked import app # SOAP services are distinct wsgi applications, we should use dispatcher # middleware to bring all aps together app.wsgi_app = DispatcherMiddleware( app.wsgi_app, {'/soap': WsgiApplication(spyned.create_app(app))}) if __name__ == '__main__': app.run()
from spyne.model.complex import Iterable from spyne.model.primitive import Integer from spyne.server.wsgi import WsgiApplication from wsgiref.simple_server import make_server from spyne.protocol.soap import Soap11 class Fibonacci(ServiceBase): @srpc(Integer,_returns=Iterable(Integer)) def fib(n): final = [] a, b = 0, 1 final.append(a) final.append(b) for i in range(n - 2): a, b = b, a + b final.append(a) return final if __name__=='__main__': app = Application([Fibonacci], 'spyne.examples.hello.http', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) wsgi_app = WsgiApplication(app) server = make_server('127.0.0.1', 7859, wsgi_app) print("server: http://127.0.0.1:7859") print("wsdl: http://localhost:7859/?wsdl") server.serve_forever()
def Ping( context, pingMessage ): if pingMessage == "Ping": return "Pong" else raise Fault( faultcode = 'Client.MessageFault', faultstring = 'pingMessage was not "Ping"' ) @rpc( Unicode, _returns = PrinterStatus ) def Status( context, printerName ): pass @rpc( Unicode, _returns = Iterable( Unicode ) ) def ListPrinters( context, areaName ): areaPrinters = printers.get(areaName, False) if not areaPrinters: raise Fault( faultcode = 'Client.ArgumentFault', faultstring = "The given areaName was not found" ) for printer in areaPrinters: yield printer @rpc( _returns = Iterable( Unicode ) ) def ListAreas( context ): for area in printers: yield area app = Application( [ HelloWorldService ], tns = 'edu.rpi.PrinterStatusServer', in_protocol = HttpRpc( validator = "soft" ), out_protocol = JsonDocument() ) if __name__ == "__main__": from wsgiref.simple_server import make_server application = WsgiApplication( app ) server = make_server( '0.0.0.0', 8000, application ) server.serve_forever()
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(), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext( server, { 'QUERY_STRING': 'ccm_c_s=abc&ccm_c_i=123&ccm_i=456&ccm_s=def', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) # # Here's what this is supposed to return: # # <div class="some_callResponse"><div class="some_callResult"> # <div class="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> # elt = html.fromstring(''.join(ctx.out_string)) print html.tostring(elt, pretty_print=True) 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
class HelloWorldService(ServiceBase): @srpc(_returns=Array(Permission)) def simple(): return v @srpc(_returns=Permission.customize(max_occurs=float('inf'))) def complex(): return v 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(validator='soft'), out_protocol=XmlDocument(), ) wsgi_application = WsgiApplication(application) server = make_server('127.0.0.1', 8000, wsgi_application) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server.serve_forever()
def confirm_deposit(ctx, request): data = { "messageName": "receive_deposit", "tenantId": "3", "correlationKeys": { "bank": { "value": request.bank_detail, "type": "String" } }, "processVariables": { "success": { "value": "true", "type": "boolean" } } } r = requests.post('http://localhost:8080/engine-rest/message', json=data) return PaymentGatewayResponse(status="Success") wallet_app = Application([WalletService], tns='soa.logistic.wallet', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_wallet = WsgiApplication(wallet_app) wallet_server = make_server('0.0.0.0', 5006, wsgi_wallet)
class HelloWorldService(ServiceBase): @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=JsonDocument()) 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()
"value": order_requests[0].receiver_name, "type": "string" }, "additional_detail": { "value": order_requests[0].additional_detail, "type": "string" } } } r = requests.post( 'http://localhost:8080/engine-rest/process-definition/key/Process_1/tenant-id/1/start', json=data) r = r.json() sleep(2) r = requests.get( 'http://localhost:9999/order', headers={'Authorization': order_requests[0].sender_secret_key}) r = r.json() return [ OrderResponse(status="Success", order_unique_id=r[-1]['unique_id']) ] place_order_app = Application([OrderService], tns='soa.logistic.order', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_place_order = WsgiApplication(place_order_app) place_order_server = make_server('0.0.0.0', 5005, wsgi_place_order)
from io import BytesIO from spyne.server.wsgi import WsgiApplication from lxml import etree from soapser.soap import app from soapser import WSDL_URL wsdl = WsgiApplication(app).doc.wsdl11 wsdl.build_interface_document(WSDL_URL) b = BytesIO(wsdl.get_interface_document()) parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(b, parser=parser) tree.write('/tmp/soapser.wsdl', pretty_print=True, xml_declaration=True)
from myemail import webEmail from flask import Flask, request, render_template, flash, url_for, redirect, escape, jsonify from flask_wtf import FlaskForm, CsrfProtect from wtforms import * from wtforms.validators import * from werkzeug.wsgi import DispatcherMiddleware from spyne.server.wsgi import WsgiApplication import spyned app = Flask(__name__) app.config["SECRET_KEY"] = "123456" app.wsgi_app = DispatcherMiddleware(app.wsgi_app, { '/soap': WsgiApplication(spyned.create_app(app)) }) # app.config.from_object('settings') # app.config["WTF_CSRF_ENABLED"] = True # CsrfProtect(app) class emailForm(FlaskForm): email = StringField(label="电子邮箱地址", validators=[DataRequired()]) title = StringField(label="邮件标题", validators=[DataRequired()]) body = TextAreaField(label="邮件内容", validators=[DataRequired()]) file = FileField(label="上传附件") submit = SubmitField(label="提交")
] class Bike(Vehicle): _type_info = [ ('size', Integer), ] class Garage(ComplexModel): _type_info = [ ('vehicles', Array(Vehicle)), ] class SomeService(ServiceBase): @rpc(_returns=Garage) def get_garage_dump(self): return Garage(vehicles=[ Car(color="blue", speed=100, owner="Simba"), Bike(size=58, owner="Nala"), ]) application = Application([SomeService], 'tns', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(polymorphic=True)) sys.exit(cherry_graft_and_start(WsgiApplication(application)))
from wsgiref.simple_server import make_server from spyne.server.wsgi import WsgiApplication from . import _cli_string, _ReverseProxied from ..config import settings from ..services import soap # Setup logging. log_level = logging.INFO if settings.DEBUG else logging.ERROR logging.basicConfig(level=log_level) logging.getLogger('spyne.protocol.xml').setLevel(log_level) #: WSGI application instance. application = WsgiApplication(soap.application) if settings.REVERSE_PROXIED: application = _ReverseProxied(application) def debugserver(host, port): """ Run the webservice with the Python built-in HTTP server. """ sys.stderr.write('Listening on http://%s:%d/\n' % (host, port)) sys.stderr.write('WDSL file is at http://%s:%d/?wsdl\n' % (host, port)) make_server(host, port, application).serve_forever() def main(): """
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
#!/usr/bin/env python3 import logging from spyne.server.wsgi import WsgiApplication from werkzeug.middleware.dispatcher import DispatcherMiddleware from apps.flasked import app from apps.soap_app import soap my_apps = { '/trembita': WsgiApplication(soap(app)), } app.wsgi_app = DispatcherMiddleware(app.wsgi_app, my_apps) llevel = logging.DEBUG if app.config.get('DEBUG') else logging.INFO soap_hendler = logging.FileHandler('./logs/standart.log') soap_hendler.setFormatter( logging.Formatter( '[%(asctime)s] [%(process)d] [%(levelname)s] %(name)s: %(message)s')) app.logger.setLevel(llevel) app.logger.addHandler(soap_hendler) logging.getLogger('spyne.protocol.xml').setLevel(llevel) if __name__ == '__main__': app.run( host=app.config.get('APP_HOST'), port=app.config.get('APP_PORT'),
def test_rpc(self): import sqlalchemy from sqlalchemy import sql class KeyValuePair(TableModel, self.DeclarativeBase): __tablename__ = 'key_value_store' __namespace__ = 'punk' key = Column(sqlalchemy.String(100), nullable=False, primary_key=True) value = Column(sqlalchemy.String, nullable=False) self.metadata.create_all(self.engine) import hashlib session = self.Session() for i in range(1, 10): key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() session.add(KeyValuePair(key=key, value=value)) session.commit() from spyne.service import ServiceBase from spyne.model.complex import Array from spyne.model.primitive import String class Service(ServiceBase): @rpc(String(max_occurs='unbounded'), _returns=Array(KeyValuePair), _in_variable_names={'keys': 'key'}) def get_values(ctx, keys): session = self.Session() return session.query(KeyValuePair).filter( sql.and_(KeyValuePair.key.in_(keys))).order_by( KeyValuePair.key) application = Application([Service], in_protocol=HttpRpc(), out_protocol=Soap11(), name='Service', tns='tns') server = WsgiApplication(application) initial_ctx = WsgiMethodContext( server, { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'key=1&key=2&key=3', 'PATH_INFO': '/get_values', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) i = 0 for e in ctx.out_document[0][0][0]: i += 1 key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() _key = e.find('{%s}key' % KeyValuePair.get_namespace()) _value = e.find('{%s}value' % KeyValuePair.get_namespace()) print((_key, _key.text)) print((_value, _value.text)) self.assertEquals(_key.text, key) self.assertEquals(_value.text, value)
from spyne import Application from spyne import rpc from spyne import ServiceBase from spyne import Iterable, Integer, Unicode, Array, util, AnyDict, ModelBase from spyne.protocol.soap import Soap11 from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication from suds.client import Client from spyne import Application from wsgiref.simple_server import make_server from process_quality.processquality import WMS_Interface, SAP_Interface, NH_Interface soap_app = Application([WMS_Interface, NH_Interface, SAP_Interface], 'WMS_Interface', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_app = WsgiApplication(soap_app) if __name__ == '__main__': import logging from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.info("listening to http://192.168.100.150:5001/") logging.info("wsdl is at: http://192.168.100.150:5001/?wsdl") server = make_server('127.0.0.1', 5001, wsgi_app) server.serve_forever()
def run_command(argv): status = UpdateStatus() oparser = OptionParser(usage="usage: %prog updated [options] <filename>") oparser.add_option("--directory", dest="update_dir", help="monitor dir (default is /var/cache/elbe/updates)", metavar="FILE") oparser.add_option("--repocache", dest="repo_dir", help="monitor dir (default is /var/cache/elbe/repos)", metavar="FILE") oparser.add_option("--host", dest="host", default="", help="listen host") oparser.add_option("--port", dest="port", default=8088, help="listen port") oparser.add_option("--nosign", action="store_true", dest="nosign", default=False, help="accept none signed files") oparser.add_option("--verbose", action="store_true", dest="verbose", default=False, help="force output to stdout instead of syslog") oparser.add_option("--usb", action="store_true", dest="use_usb", default=False, help="monitor USB devices") (opt, _) = oparser.parse_args(argv) status.nosign = opt.nosign status.verbose = opt.verbose if not opt.update_dir: update_dir = "/var/cache/elbe/updates" else: update_dir = opt.update_dir if not opt.repo_dir: status.repo_dir = "/var/cache/elbe/repos" else: status.repo_dir = opt.repo_dir if not os.path.isdir(update_dir): os.makedirs(update_dir) status.monitors = [] fm = FileMonitor(status, update_dir) status.monitors.append(fm) if opt.use_usb: if usbmonitor_available: um = USBMonitor(status, recursive=False) status.monitors.append(um) else: status.log( "USB Monitor has been requested. " "This requires pyudev module which could not be imported.") sys.exit(1) signal.signal(signal.SIGTERM, shutdown) for mon in status.monitors: mon.start() application = UpdateApplication([UpdateService], 'update', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) application.status = status wsgi_application = WsgiApplication(application) status.soapserver = make_server(opt.host, int(opt.port), wsgi_application) try: status.soapserver.serve_forever() except BaseException: shutdown(1, "now", status) for mon in status.monitors: mon.join()
def test_multiple(self): class SomeService(ServiceBase): @srpc(String(max_occurs='unbounded'), _returns=String) def some_call(s): print s return '\n'.join(s) app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext( server, { 'QUERY_STRING': 's=1&s=2', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join(ctx.out_string) == ( '<div class="some_callResponse">' '<div class="some_callResult">1\n2</div></div>') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join( ctx.out_string ) == '<div class="some_callResponse"><div class="some_callResult">1\n2</div></div>'
try: from wsgiref.simple_server import make_server except ImportError: logging.error("Error: example server code requires Python >= 2.5") application = Application([HelloWorldService], 'spyne.examples.events', in_protocol=HttpRpc(), out_protocol=JsonDocument()) application.event_manager.add_listener('method_call', _on_method_call) application.event_manager.add_listener('method_return_object', _on_method_return_object) application.event_manager.add_listener('method_context_constructed', _on_method_context_constructed) application.event_manager.add_listener('method_context_destroyed', _on_method_context_destroyed) wsgi_wrapper = WsgiApplication(application) wsgi_wrapper.event_manager.add_listener('wsgi_call', _on_wsgi_call) wsgi_wrapper.event_manager.add_listener('wsgi_return', _on_wsgi_return) wsgi_wrapper.event_manager.add_listener('wsgi_close', _on_wsgi_close) server = make_server('127.0.0.1', 8000, wsgi_wrapper) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server.serve_forever()
# We need the _args argument here because we only want to expose the # `a` and `b` arguments and not the `self` argument. randint = srpc(Mandatory.Integer, Mandatory.Integer, _returns=Integer, _args=('a', 'b'))(random.randint) # We need the _args argument here because `getrandbits` is a builtin, which # means it's not ready for introspection. randbits = srpc(Mandatory.UnsignedInteger, _returns=UnsignedInteger, _args=('k'))(random.getrandbits) if __name__ == '__main__': from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) application = Application([RandomService], 'spyne.examples.hello.http', in_protocol=HttpRpc(validator='soft'), out_protocol=HttpRpc()) server = make_server('127.0.0.1', 8000, WsgiApplication(application)) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server.serve_forever()
def test_multiple(self): class SomeService(ServiceBase): @srpc(String(max_occurs='unbounded'), _returns=String) def some_call(s): return '\n'.join(s) app = Application([SomeService], 'tns', HttpRpc(), HtmlMicroFormat(), Wsdl11()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 's=1&s=2', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult">1\n2</div></div>' ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert ''.join(ctx.out_string) == '<div class="some_callResponse"><div class="some_callResult">1\n2</div></div>'
def __init__(self): application = Application([HomeworkService], 'Homework-4', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) self.wsgi_application = WsgiApplication(application)
def get_olapy_server(Xmla_discover_request_handler, Xmla_execute_request_handler): application = get_spyne_app( Xmla_discover_request_handler, Xmla_execute_request_handler ) wsgi_application = WsgiApplication(application) return WSGIServer(application=wsgi_application, host=HOST, port=PORT)
def test_rpc(self): import sqlalchemy from sqlalchemy import sql class KeyValuePair(TableModel, self.DeclarativeBase): __tablename__ = 'key_value_store' __namespace__ = 'punk' key = Column(sqlalchemy.String(100), nullable=False, primary_key=True) value = Column(sqlalchemy.String, nullable=False) self.metadata.create_all(self.engine) import hashlib session = self.Session() for i in range(1, 10): key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() session.add(KeyValuePair(key=key, value=value)) session.commit() from spyne.service import ServiceBase from spyne.model.complex import Array from spyne.model.primitive import String class Service(ServiceBase): @rpc(String(max_occurs='unbounded'), _returns=Array(KeyValuePair), _in_variable_names={ 'keys': 'key' } ) def get_values(ctx, keys): session = self.Session() return session.query(KeyValuePair).filter(sql.and_( KeyValuePair.key.in_(keys) )).order_by(KeyValuePair.key) application = Application([Service], in_protocol=HttpRpc(), out_protocol=Soap11(), name='Service', tns='tns' ) server = WsgiApplication(application) initial_ctx = WsgiMethodContext(server, { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'key=1&key=2&key=3', 'PATH_INFO': '/get_values', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) i = 0 for e in ctx.out_document[0][0][0]: i+=1 key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() _key = e.find('{%s}key' % KeyValuePair.get_namespace()) _value = e.find('{%s}value' % KeyValuePair.get_namespace()) print((_key, _key.text)) print((_value, _value.text)) self.assertEquals(_key.text, key) self.assertEquals(_value.text, value)
def test_multiple(self): class SomeService(ServiceBase): @srpc(String(max_occurs='unbounded'), _returns=String) def some_call(s): print(s) return '\n'.join(s) app = Application([SomeService], 'tns', in_protocol=HttpRpc(hier_delim='_'), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 's=1&s=2', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert b''.join(ctx.out_string) == (b'<div class="some_callResponse">' b'<div class="some_callResult">1\n2</div></div>') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert b''.join(ctx.out_string) == b'<div class="some_callResponse">' \ b'<div class="some_callResult">1\n2</div></div>'
#find the most dangrous steeet by sortinng and getting top 3----------------------------------- top3 = Counter(countsaddress) top3.most_common() #print top3.most_common() #now gwt the top 3------------------------------------------------------------------------------ for key, value in top3.most_common(3): mostdangerous.append(key) #finall print======================================================= final_dict = { "total_crime": totalcrimes, "the_most_dangerous_streets": mostdangerous, "crime_type_count": crime_type_count, "event_time_count": event_time_count } yield final_dict application = Application([FindCrime], tns='snype.example.hello', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) if __name__ == "__main__": app = WsgiApplication(application) server = make_server('0.0.0.0', 8000, app) server.serve_forever()
def __init__(self, mounts=None): self.mounts = dict([(k, WsgiApplication(v)) for k,v in (mounts or {}).items()])
from spyne.application import Application from spyne.test.interop.server._service import services from spyne.protocol.http import HttpRpc from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication httprpc_soap_application = Application( services, 'spyne.test.interop.server.httprpc.soap', in_protocol=HttpRpc(), out_protocol=Soap11()) host = '127.0.0.1' port = 9753 if __name__ == '__main__': try: from wsgiref.simple_server import make_server from wsgiref.validate import validator wsgi_application = WsgiApplication(httprpc_soap_application) server = make_server(host, port, validator(wsgi_application)) logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9753)) logger.info('WSDL is at: /?wsdl') server.serve_forever() except ImportError: print("Error: example server code requires Python >= 2.5")
@rpc() def server_exception(ctx): raise Exception("Server side exception example.") @rpc() def server_fault(ctx): raise Fault("Server", "Server side fault example.") @rpc() def client_fault(ctx): raise Fault("Client", "Client side fault example") app = Application([StanSoapService], 'instana.tests.app.ask_question', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) # Use Instana middleware so we can test context passing and Soap server traces. wsgi_app = iWSGIMiddleware(WsgiApplication(app)) soapserver = make_server('127.0.0.1', 4132, wsgi_app) logging.basicConfig(level=logging.WARN) logging.getLogger('suds').setLevel(logging.WARN) logging.getLogger('suds.resolver').setLevel(logging.WARN) logging.getLogger('spyne.protocol.xml').setLevel(logging.WARN) logging.getLogger('spyne.model.complex').setLevel(logging.WARN) if __name__ == '__main__': soapserver.serve_forever()
def test_complex(self): class SomeService(ServiceBase): @srpc(CCM, _returns=CCM) def some_call(ccm): return ccm app = Application([SomeService], 'tns', in_protocol=HttpRpc(hier_delim="_"), out_protocol=HtmlRowTable(field_name_attr='class')) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs(server, 'some_call', ccm_c_s='abc', ccm_c_i='123', ccm_i='456', ccm_s='def') elt = html.fromstring(out_string) show(elt, "TestHtmlRowTable.test_complex") # Here's what this is supposed to return """ <table class="CCM"> <tbody> <tr> <th class="i">i</th> <td class="i">456</td> </tr> <tr class="c"> <th class="c">c</th> <td class="c"> <table class="c"> <tbody> <tr> <th class="i">i</th> <td class="i">123</td> </tr> <tr> <th class="s">s</th> <td class="s">abc</td> </tr> </tbody> </table> </td> </tr> <tr> <th class="s">s</th> <td class="s">def</td> </tr> </tbody> </table> """ print(html.tostring(elt, pretty_print=True)) resp = elt.find_class('CCM') assert len(resp) == 1 assert elt.xpath('tbody/tr/th[@class="i"]/text()')[0] == 'i' assert elt.xpath('tbody/tr/td[@class="i"]/text()')[0] == '456' assert elt.xpath( 'tbody/tr/td[@class="c"]//th[@class="i"]/text()')[0] == 'i' assert elt.xpath( 'tbody/tr/td[@class="c"]//td[@class="i"]/text()')[0] == '123' assert elt.xpath( 'tbody/tr/td[@class="c"]//th[@class="s"]/text()')[0] == 's' assert elt.xpath( 'tbody/tr/td[@class="c"]//td[@class="s"]/text()')[0] == 'abc' assert elt.xpath('tbody/tr/th[@class="s"]/text()')[0] == 's' assert elt.xpath('tbody/tr/td[@class="s"]/text()')[0] == 'def'
cookie.load(http_cookie) if "session-id" not in cookie: raise UnauthenticatedError() session_cookie = cookie["session-id"].value session_id = tuple(base64.urlsafe_b64decode(session_cookie).split("\0", 1)) if not session_id in session_db: raise AuthenticationError(session_id[0]) ctx.udc = session_id[0] # user name UserService.event_manager.add_listener('method_call', _on_method_call) if __name__=='__main__': from spyne.util.wsgi_wrapper import run_twisted logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.getLogger('twisted').setLevel(logging.DEBUG) application = Application([UserService], tns='spyne.examples.authentication', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) twisted_apps = [ (WsgiApplication(application), 'app'), ] sys.exit(run_twisted(twisted_apps, 8000))
def test_complex(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM i = Integer s = String class SomeService(ServiceBase): @srpc(CCM, _returns=CCM) def some_call(ccm): return CCM(c=ccm.c,i=ccm.i, s=ccm.s) app = Application([SomeService], 'tns', in_protocol=HttpRpc(hier_delim='_'), out_protocol=HtmlMicroFormat()) server = WsgiApplication(app) initial_ctx = WsgiMethodContext(server, { 'QUERY_STRING': 'ccm_c_s=abc&ccm_c_i=123&ccm_i=456&ccm_s=def', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) # # Here's what this is supposed to return: # # <div class="some_callResponse"> # <div class="some_callResult"> # <div class="i">456</div> # <div class="c"> # <div class="i">123</div> # <div class="s">abc</div> # </div> # <div class="s">def</div> # </div> # </div> # elt = html.fromstring(''.join(ctx.out_string)) print(html.tostring(elt, pretty_print=True)) resp = elt.find_class('some_callResponse') assert len(resp) == 1 res = resp[0].find_class('some_callResult') assert len(res) == 1 i = res[0].findall('div[@class="i"]') assert len(i) == 1 assert i[0].text == '456' c = res[0].findall('div[@class="c"]') assert len(c) == 1 c_i = c[0].findall('div[@class="i"]') assert len(c_i) == 1 assert c_i[0].text == '123' c_s = c[0].findall('div[@class="s"]') assert len(c_s) == 1 assert c_s[0].text == 'abc' s = res[0].findall('div[@class="s"]') assert len(s) == 1 assert s[0].text == 'def'
def test_complex_array(self): v = [ CM(i=1, s='a'), CM(i=2, s='b'), CM(i=3, s='c'), CM(i=4, s='d'), ] class SomeService(ServiceBase): @srpc(_returns=Array(CM)) def some_call(): return v app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlRowTable()) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs(server) show(html.fromstring(out_string), 'TestHtmlRowTable.test_complex_array') #FIXME: Needs a proper test with xpaths and all. assert out_string == \ '<div xmlns="http://www.w3.org/1999/xhtml">' \ '<table xmlns="http://www.w3.org/1999/xhtml" class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">1</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">a</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table xmlns="http://www.w3.org/1999/xhtml" class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">2</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">b</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table xmlns="http://www.w3.org/1999/xhtml" class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">3</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">c</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table xmlns="http://www.w3.org/1999/xhtml" class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">4</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">d</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '</div>'