def test_complex_array(self): class SomeService(ServiceBase): @srpc(CCM, _returns=Array(CCM)) def some_call(ccm): return [ccm] * 5 app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlTable(field_name_attr='class')) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs( server, ccm_i='456', ccm_s='def', ccm_c_i='123', ccm_c_s='abc', ) from lxml import etree elt = etree.fromstring(out_string) print(etree.tostring(elt, pretty_print=True)) elt = html.fromstring(out_string) resp = elt.find_class('some_callResponse') assert len(resp) == 1 row, = elt[0] # thead cell = row.findall('th[@class="i"]') assert len(cell) == 1 assert cell[0].text == 'i' cell = row.findall('th[@class="s"]') assert len(cell) == 1 assert cell[0].text == 's' for row in elt[1]: # tbody cell = row.xpath('td[@class="i"]') assert len(cell) == 1 assert cell[0].text == '456' cell = row.xpath('td[@class="c"]//td[@class="i"]') assert len(cell) == 1 assert cell[0].text == '123' cell = row.xpath('td[@class="c"]//td[@class="s"]') assert len(cell) == 1 assert cell[0].text == 'abc' cell = row.xpath('td[@class="s"]') assert len(cell) == 1 assert cell[0].text == 'def'
def setUp(self): class SomeService(Service): @srpc(String, _returns=String) def echo_string(s): return s app = Application([SomeService], 'tns', in_protocol=HttpRpc(validator='soft'), out_protocol=HttpRpc(), ) self.app = WsgiApplication(app)
def register_service(self, service): spyne_app = Application([service], tns=service.__target_namespace__, name=service.__name__, in_protocol=service.__in_protocol__, out_protocol=service.__out_protocol__) spyne_app.event_manager.add_listener('method_call', self._on_method_call) spyne_app.event_manager.add_listener('method_return_object', self._on_method_return_object) wsgi_app = WsgiApplication(spyne_app) self.services[service.__service_url_path__] = wsgi_app
def test_array_iterable(self): class SomeService(ServiceBase): @rpc(Array(Unicode), Iterable(Unicode)) def some_call(ctx, a, b): pass app = Application([SomeService], 'tns', in_protocol=Soap11(), out_protocol=Soap11(cleanup_namespaces=True)) server = WsgiApplication(app)
def test_http_headers(self): d = datetime(year=2013, month=1, day=1) string = ['hey', 'yo'] class ResponseHeader(ComplexModel): _type_info = { 'Set-Cookie': String(max_occurs='unbounded'), 'Expires': DateTime } class SomeService(ServiceBase): __out_header__ = ResponseHeader @rpc(String) def some_call(ctx, s): assert s is not None ctx.out_header = ResponseHeader(**{'Set-Cookie': string, 'Expires': d}) def start_response(code, headers): print(headers) assert len([s for s in string if ('Set-Cookie', s) in headers]) == len(string) assert dict(headers)['Expires'] == 'Tue, 01 Jan 2013 00:00:00 GMT' app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc()) wsgi_app = WsgiApplication(app) req_dict = { 'SCRIPT_NAME': '', 'QUERY_STRING': '&s=foo', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', 'SERVER_PORT': "9999", 'wsgi.url_scheme': 'http', 'wsgi.version': (1,0), 'wsgi.input': StringIO(), 'wsgi.errors': StringIO(), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': True, } ret = wsgi_app(req_dict, start_response) print(list(ret)) wsgi_app = wsgiref_validator(wsgi_app) ret = wsgi_app(req_dict, start_response) assert list(ret) == [b'']
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()
def get_wsgi_application(mdx_engine): """ :param mdx_engine: MdxEngine instance :return: Wsgi Application """ discover_request_hanlder = XmlaDiscoverReqHandler(mdx_engine) execute_request_hanlder = XmlaExecuteReqHandler(mdx_engine) application = get_spyne_app(discover_request_hanlder, execute_request_hanlder) # validator='soft' or nothing, this is important because spyne doesn't # support encodingStyle until now !!!! return WsgiApplication(application)
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
def test_complex_array(self): class SomeService(ServiceBase): @srpc(CCM, _returns=Array(CCM)) def some_call(ccm): return [ccm] * 5 app = Application( [SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlColumnTable(field_type_name_attr=None)) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs( server, ccm_i='456', ccm_s='def', ccm_c_i='123', ccm_c_s='abc', ) elt = etree.fromstring(out_string) show(elt, 'TestHtmlColumnTable.test_complex_array') elt = html.fromstring(out_string) row, = elt[0] # thead cell = row.findall('th[@class="i"]') assert len(cell) == 1 assert cell[0].text == 'i' cell = row.findall('th[@class="s"]') assert len(cell) == 1 assert cell[0].text == 's' for row in elt[1]: # tbody cell = row.xpath('td[@class="i"]') assert len(cell) == 1 assert cell[0].text == '456' cell = row.xpath('td[@class="c"]//td[@class="i"]') assert len(cell) == 1 assert cell[0].text == '123' cell = row.xpath('td[@class="c"]//td[@class="s"]') assert len(cell) == 1 assert cell[0].text == 'abc' cell = row.xpath('td[@class="s"]') assert len(cell) == 1 assert cell[0].text == 'def'
def webserverFun(): soap_app = Application([IMonitorWebServices], 'IMonitorServices', in_protocol=Soap11(validator="lxml"), out_protocol=Soap11()) wsgi_app = WsgiApplication(soap_app) # svr = simple_server.make_server(ip,port,wsgi_app) svr = mt_wsgi((ip, port), simple_server.WSGIRequestHandler) svr.set_app(wsgi_app) try: svr.serve_forever() finally: svr.server_close()
def __publish(self, soap_type): app = Application(self.__services, self.__tns, self.__name, soap_type(validator="lxml"), soap_type()) if self.__event_handler_dict is not None: for key, value in self.__event_handler_dict.items(): app.event_manager.add_listener(key, value) wsgi_app = WsgiApplication(app) server = make_server(self.__host, self.__port, wsgi_app) self.__server = server self.__thread = _PublishThread(server) self.__thread.start() print("Service, %s, published at %s." % (self.__name, time.strftime(self.__time_format)), file=self.__log_target)
def main(): try: from wsgiref.simple_server import make_server from wsgiref.validate import validator wsgi_application = WsgiApplication(soap_application) server = make_server(host, port, validator(wsgi_application)) logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9754)) logger.info('WSDL is at: /?wsdl') server.serve_forever() except ImportError: print("Error: example server code requires Python >= 2.5")
def test_cookie_parse(self): string = 'some_string' class RequestHeader(ComplexModel): some_field = String class SomeService(ServiceBase): __in_header__ = RequestHeader @rpc(String) def some_call(ctx, s): assert ctx.in_header.some_field == string def start_response(code, headers): assert code == HTTP_200 c = SimpleCookie() c['some_field'] = string app = Application([SomeService], 'tns', in_protocol=HttpRpc(parse_cookie=True), out_protocol=HttpRpc()) wsgi_app = WsgiApplication(app) req_dict = { 'SCRIPT_NAME': '', 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', 'SERVER_PORT': "9999", 'HTTP_COOKIE': str(c), 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), 'wsgi.input': StringIO(), 'wsgi.errors': StringIO(), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': True, } ret = wsgi_app(req_dict, start_response) print(ret) wsgi_app = wsgiref_validator(wsgi_app) ret = wsgi_app(req_dict, start_response) print(ret)
def test_string_array(self): class SomeService(ServiceBase): @srpc(String(max_occurs='unbounded'), _returns=Array(String)) def some_call(s): return s app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlTable(fields_as='rows')) server = WsgiApplication(app) out_string = call_wsgi_app(server, body_pairs=(('s', '1'), ('s', '2'))) assert out_string == '<table class="some_callResponse"><tr><td>1</td></tr><tr><td>2</td></tr></table>'
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 __init__(self, mounts=None): self.mounts = {} for k, v in (mounts or {}).items(): if isinstance(v, Application): app = WsgiApplication(v) else: assert callable(v), "%r is not a valid wsgi app." % v app = v if k in ('', '/'): self.default = app else: self.mounts[k] = app
def tr069_server(state_machine_manager: StateMachineManager) -> None: """ TR-069 server Inputs: - acs_to_cpe_queue = instance of Queue containing messages from parent process/thread to be sent to CPE - cpe_to_acs_queue = instance of Queue containing messages from CPE to be sent to parent process/thread """ config = load_service_config("enodebd") AutoConfigServer.set_state_machine_manager(state_machine_manager) app = Tr069Application( [AutoConfigServer], CWMP_NS, in_protocol=Tr069Soap11(validator='soft'), out_protocol=Tr069Soap11(), ) wsgi_app = WsgiApplication(app) try: ip_address = get_ip_from_if(config['tr069']['interface']) except (ValueError, KeyError) as e: # Interrupt main thread since process should not continue without TR-069 _thread.interrupt_main() raise e socket.setdefaulttimeout(SOCKET_TIMEOUT) logger.info( 'Starting TR-069 server on %s:%s', ip_address, config['tr069']['port'], ) server = make_server( ip_address, config['tr069']['port'], wsgi_app, WSGIServer, tr069_WSGIRequestHandler, ) # Note: use single-thread server, to avoid state contention try: server.serve_forever() finally: # Log error and interrupt main thread, to ensure that entire process # is restarted if this thread exits logger.error('Hit error in TR-069 thread. Interrupting main thread.') _thread.interrupt_main()
def test_http_headers(self): DATE = datetime(year=2013, month=1, day=1) STR = 'hey' class ResponseHeader(ComplexModel): _type_info = { 'Set-Cookie': String(max_occurs='unbounded'), 'Expires': DateTime } class SomeService(ServiceBase): __out_header__ = ResponseHeader @rpc(String) def some_call(ctx, s): assert s is not None ctx.out_header = ResponseHeader(**{ 'Set-Cookie': STR, 'Expires': DATE }) def start_response(code, headers): assert dict(headers)['Set-Cookie'] == STR assert dict(headers)['Expires'] == 'Tue, 01 Jan 2013 00:00:00 GMT' ret = ''.join( validator( WsgiApplication( Application( [SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc())))({ 'SCRIPT_NAME': '', 'QUERY_STRING': '&s=' + STR, 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', 'SERVER_PORT': "9999", 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), 'wsgi.input': StringIO(), 'wsgi.errors': StringIO(), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': True, }, start_response)) assert ret == ''
def _get_twisted_resource(key, app): if isinstance(app, Resource): app.prepath = key return app if isinstance(app, Static): return StaticFile(app.root_path) if isinstance(app, Application): app = WsgiApplication(app) if isinstance(app, (WsgiApplication, WsgiMounter)): return WSGIResource(reactor, reactor.getThreadPool(), app) raise Exception("%r ile ne yapacagimi bilemedim." % app)
def test_mtom(self): FILE_NAME = 'EA055406-5881-4F02-A3DC-9A5A7510D018.dat' TNS = 'http://gib.gov.tr/vedop3/eFatura' class SomeService(Service): @rpc(Unicode(sub_name="fileName"), ByteArray(sub_name='binaryData'), ByteArray(sub_name="hash"), _returns=Unicode) def documentRequest(ctx, file_name, file_data, data_hash): assert file_name == FILE_NAME assert file_data == (b'sample data', ) return file_name app = Application([SomeService], tns=TNS, in_protocol=Soap12(), out_protocol=Soap12()) server = WsgiApplication(app) response = etree.fromstring(b''.join( server( { 'QUERY_STRING': '', 'PATH_INFO': '/call', 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'Content-Type: multipart/related; ' 'type="application/xop+xml"; ' 'boundary="uuid:2e53e161-b47f-444a-b594-eb6b72e76997"; ' 'start="<*****@*****.**>"; ' 'start-info="application/soap+xml"; action="sendDocument"', 'wsgi.input': BytesIO(MTOM_REQUEST.replace(b"\n", b"\r\n")) }, start_response, "http://null"))) response_str = etree.tostring(response, pretty_print=True) print(response_str) nsdict = dict(tns=TNS) assert etree.fromstring(response_str) \ .xpath(".//tns:documentRequestResult/text()", namespaces=nsdict) \ == [FILE_NAME]
def test_fault_generation(self): class SoapException(ServiceBase): @srpc() def soap_exception(): raise Fault( "Client.Plausible", "A plausible fault", 'http://faultactor.example.com') app = Application([SoapException], 'tns', in_protocol=Soap12(), out_protocol=Soap12()) req = """ <soap12env:Envelope xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:tns="tns"> <soap12env:Body> <tns:soap_exception/> </soap12env:Body> </soap12env:Envelope> """ server = WsgiApplication(app) response = etree.fromstring(''.join(server({ 'QUERY_STRING': '', 'PATH_INFO': '/call', 'REQUEST_METHOD': 'GET', 'wsgi.input': StringIO(req) }, start_response, "http://null"))) response_str = etree.tostring(response, pretty_print=True) print(response_str) expected = """ <soap12env:Envelope xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope"> <soap12env:Body> <soap12env:Fault> <soap12env:Reason> <soap12env:Text xml:lang="en">A plausible fault</soap12env:Text> </soap12env:Reason> <soap12env:Role>http://faultactor.example.com</soap12env:Role> <soap12env:Code> <soap12env:Value>soap12env:Sender</soap12env:Value> <soap12env:Subcode> <soap12env:Value>Plausible</soap12env:Value> </soap12env:Subcode> </soap12env:Code> </soap12env:Fault> </soap12env:Body> </soap12env:Envelope>""" if not LXMLOutputChecker().check_output(expected, response_str, PARSE_XML): raise Exception("Got: %s but expected: %s" % (response_str, expected))
def main(): try: from wsgiref.simple_server import make_server from wsgiref.validate import validator if port[0] == 0: port[0] = get_open_port() wsgi_application = WsgiApplication(msgpackrpc_application) server = make_server(host, port[0], validator(wsgi_application)) logger.info('Starting interop server at %s:%s.' % (host, port[0])) logger.info('WSDL is at: /?wsdl') server.serve_forever() except ImportError: print("Error: example server code requires Python >= 2.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()
def propagation_service(fcgi=True): if fcgi is False: def _on_method_return_object(ctx): ctx.transport.resp_headers['Access-Control-Allow-Origin'] = "*" ctx.transport.resp_headers[ 'Cache-Control'] = "public,max-age=86400" # tbd PropagationService.event_manager.add_listener( 'method_return_object', _on_method_return_object) json = Application([PropagationService], tns='swhv.service.propagation', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) return WsgiApplication(json)
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()
def __run_service(self, service): app = Application([service], 'tns', in_protocol=HttpRpc(), out_protocol=Soap11()) server = WsgiApplication(app) return_string = b''.join(server({ 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'text/xml; charset=utf8', 'SERVER_NAME': 'localhost', 'wsgi.input': BytesIO(b""), }, start_response, "http://null")) elt = etree.fromstring(return_string) print(etree.tostring(elt, pretty_print=True)) return elt, app.interface.nsmap
def wsgi_soap11_application(services, tns='spyne.simple.soap', validator=None, name=None): """Wraps `services` argument inside a WsgiApplication 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.wsgi import WsgiApplication application = Application(services, tns, name=name, in_protocol=Soap11(validator=validator), out_protocol=Soap11()) return WsgiApplication(application)
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_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 __run_service(self, service): app = Application([service], 'tns', in_protocol=HttpRpc(), out_protocol=Soap11()) server = WsgiApplication(app) return_string = ''.join( server( { 'QUERY_STRING': '', 'PATH_INFO': '/some_call', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', }, start_response, "http://null")) elt = etree.fromstring(''.join(return_string)) print etree.tostring(elt, pretty_print=True) return elt, app.interface.nsmap