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 get_object_as_json(o, cls, ignore_wrappers=True, complex_as=list, encoding='utf8', polymorphic=False): prot = JsonDocument(ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic) ctx = FakeContext(out_document=[prot._object_to_doc(cls,o)]) prot.create_out_string(ctx, encoding) return ''.join(ctx.out_string)
def start_core(config): subconfig = config.services['core'] if subconfig.subapps is None: subconfig.subapps = {} subconfig.subapps.update({ '': Application( [CoreReaderServices], tns='https://jmap.io/', name='CoreServices', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(), config=config, ), 'api': Application( [ MailReaderServices, MailWriterServices, ], tns='https://jmap.io/', name='ApiServices', in_protocol=JsonDocument(validator='soft'), out_protocol=JsonDocument(), config=config, ) }) return subconfig.gen_site()
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 get_object_as_json(o, cls=None, ignore_wrappers=True, complex_as=list, encoding="utf8", polymorphic=False): if cls is None: cls = o.__class__ prot = JsonDocument(ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic) ctx = FakeContext(out_document=[prot._object_to_doc(cls, o)]) prot.create_out_string(ctx, encoding) return "".join(ctx.out_string)
def get_object_as_json_doc(o, cls=None, ignore_wrappers=True, complex_as=list, polymorphic=False, indent=None, **kwargs): if cls is None: cls = o.__class__ prot = JsonDocument(ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic, indent=indent, **kwargs) return prot._object_to_doc(cls, o)
def get_object_as_json(o, cls=None, ignore_wrappers=True, complex_as=list, encoding='utf8', polymorphic=False, indent=None, **kwargs): if cls is None: cls = o.__class__ prot = JsonDocument(ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic, indent=indent, **kwargs) ctx = FakeContext(out_document=[prot._object_to_doc(cls, o)]) prot.create_out_string(ctx, encoding) return b''.join(ctx.out_string)
def test_invalid_input(self): class SomeService(ServiceBase): pass app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument()) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [b'{'] ctx, = server.generate_contexts(initial_ctx, in_string_charset='utf8') assert ctx.in_error.faultcode == 'Client.JsonDecodeError'
def say_hello_as_json_file(ctx, name, times): ctx.out_protocol = JsonDocument() # see how we don't set the mime type but it's still present in the # response headers return _say_hello(ctx, name, times, 'txt')
def run(self): # Instantiate the application by giving it: # * The list of services it should wrap, # * A namespace string. # * An input protocol. # * An output protocol. application = Application( [CryptoassetsRPCService], 'spyne.examples.hello.http', # The input protocol is set as HttpRpc to make our service easy to # call. Input validation via the 'soft' engine is enabled. (which is # actually the the only validation method for HttpRpc.) in_protocol=HttpRpc(validator='soft'), # The ignore_wrappers parameter to JsonDocument simplifies the reponse # dict by skipping outer response structures that are redundant when # the client knows what object to expect. out_protocol=JsonDocument(ignore_wrappers=True), ) # Now that we have our application, we must wrap it inside a transport. # In this case, we use Spyne's standard Wsgi wrapper. Spyne supports # popular Http wrappers like Twisted, Django, Pyramid, etc. as well as # a ZeroMQ (REQ/REP) wrapper. wsgi_application = WsgiApplication(application) # More daemon boilerplate self.server = make_server(self.ip, self.port, wsgi_application) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") self.server.serve_forever()
def create_http_application(self): app = HydraSoapApplication(applications, tns='hydra.base', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) return app
def __init__(self): from wsgiref.simple_server import make_server self.application = Application( [RPCReceiver.HelloSwitchService], tns='spyne.examples.hello', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) self.wsgi_app = WsgiApplication(self.application) self.server = make_server('0.0.0.0', 7846, self.wsgi_app)
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 start_a2bs(config): subconfig = config.services.getwrite( 'web', HttpListener( host='0.0.0.0', port=9271, disabled=False, _subapps=[ StaticFileServer(url='assets', path=abspath('assets'), list_contents=False) ], )) services = [ TestServices, CardReaderServices, CardWriterServices, SipBuddyReaderServices, SipBuddyWriterServices, ExtReaderServices, ExtWriterServices, ] subconfig.subapps['json'] = \ Application(services, tns='a2bs.web', name='A2BillingJson', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(), config=config, ) subconfig.subapps['xml'] = \ Application(services, tns='a2bs.web', name='A2BillingXml', in_protocol=HttpRpc(validator='soft'), out_protocol=XmlDocument(), config=config, ) subconfig.subapps[''] = \ Application(services, tns='a2bs.web', name='A2BillingHtml', in_protocol=HttpRpc(validator='soft'), out_protocol=HtmlMicroFormat(), config=config, ) site = subconfig.gen_site() logger.info("listening for a2billing http endpoint %s:%d", subconfig.host, subconfig.port) return reactor.listenTCP(subconfig.port, site, interface=subconfig.host), None
def assert_json_ok(self, suffix, _operation_name = None, _in_message_name=None): '''helper to test json requests''' # setup app = self.get_app(JsonDocument(validator='soft'), suffix, _operation_name, _in_message_name) function_name, operation_name, request_name = self.get_function_names(suffix, _operation_name, _in_message_name) json_input_body = '{"'+ request_name+ '": {"string": "test", "times": 2}}' # check json operation succeeded resp = app.post('/', json_input_body) self.assert_response_ok(resp)
class SomeJsonService(spyne.Service): __service_url_path__ = '/json/anotherservice' __in_protocol__ = HttpRpc(validator='soft') __out_protocol__ = JsonDocument(ignore_wrappers=True) @spyne.srpc(Unicode, Integer, _returns=Iterable(Unicode)) def echo(str, cnt): for i in range(cnt): yield str @spyne.srpc(Unicode, _returns=AnswerServiceResponse) def answer(str): return AnswerServiceResponse(dummy_str='answer is', dummy_num=42)
def init_app(config): subconfig = config.services["root"] app = Application( [TfbOrmService, TfbRawService, TfbSimpleService], tns="http://techempower.com/benchmarks/Python/Spyne", in_protocol=HttpRpc(), out_protocol=JsonDocument(), config=config, ) if subconfig.subapps is None: subconfig.subapps = {} subconfig.subapps.update({"": app}) return subconfig.gen_site()
def test_callback_name(self): callback_name = 'some_callback' retval = 42 class SomeService(ServiceBase): @srpc(_returns=Integer) def yay(): return retval app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonP(callback_name)) server = NullServer(app, ostr=True) assert ''.join( server.service.yay()) == '%s(%d);' % (callback_name, retval)
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 rest_get(flask_app): Sget = Application( [DictWage], tns=flask_app.config.get('NAMESPACE'), name='DictWage', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(), ) def _flask_config_context(ctx): ctx.udc = UserDefinedContext(flask_app) Sget.event_manager.add_listener( 'method_call', _flask_config_context ) return Sget
def geometry_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 GeometryService.event_manager.add_listener('method_return_object', _on_method_return_object) json = Application([GeometryService], tns='swhv.service.geometry.json', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) msgpack = Application([GeometryService], tns='swhv.service.geometry.msgpack', in_protocol=HttpRpc(validator='soft'), out_protocol=MessagePackDocument()) return WsgiMounter({'json': json, 'msgpack': msgpack})
def assert_json_ok(self, suffix, _operation_name=None, _in_message_name=None): """helper to test json requests""" # setup app = self.get_app(JsonDocument(validator='soft'), suffix, _operation_name, _in_message_name) function_name, operation_name, request_name = self.get_function_names( suffix, _operation_name, _in_message_name) json_input_body = '{"' + request_name + '": {"string": "test", ' \ '"times": 2}}' # check json operation succeeded resp = app.post('/', json_input_body, content_type='application/json; charset=utf8') self.assert_response_ok(resp)
def test_callback_name(self): callback_name = 'some_callback' retval = 42 class SomeService(ServiceBase): @srpc(_returns=Integer) def yay(): return retval app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonP(callback_name)) server = NullServer(app, ostr=True) ret = server.service.yay() ret = list(ret) print(ret) assert b''.join(ret) == b''.join((callback_name.encode('utf8'), b'(', str(retval).encode('utf8'), b');'))
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', # The input protocol is set as HttpRpc to make our service easy to call. in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(ignore_wrappers=True), ) # Use `method_call` hook to pass flask config to each service method # context. But if you have any better ideas do it, make a pull request. # NOTE. I refuse idea to wrap each call into Flask application context # because in fact we inside Spyne app context, not the Flask one. def _flask_config_context(ctx): ctx.udc = UserDefinedContext(flask_app.config) application.event_manager.add_listener('method_call', _flask_config_context) return application
def main(): logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.getLogger('sqlalchemy.engine.base.Engine').setLevel(logging.DEBUG) application = MyApplication( [UserManagerService], 'spyne.examples.user_manager', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(ignore_wrappers=1), ) wsgi_app = WsgiApplication(application) server = make_server('127.0.0.1', 8000, wsgi_app) TableModel.Attributes.sqla_metadata.create_all(checkfirst=True) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") return server.serve_forever()
def test_callback_name(self): callback_name = 'some_callback' class SomeComplexModel(ComplexModel): i = Integer s = Unicode v1 = 42 v2 = SomeComplexModel(i=42, s='foo') class SomeService(ServiceBase): @srpc(_returns=Integer) def yay(): return v1 @srpc(_returns=SomeComplexModel) def complex(): return v2 app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonP(callback_name)) server = NullServer(app, ostr=True) ret = server.service.yay() ret = list(ret) print(b''.join(ret)) assert b''.join(ret) == b''.join((callback_name.encode('utf8'), b'(', str(v1).encode('utf8'), b');')) ret = server.service.complex() ret = list(ret) print(b''.join(ret)) assert b''.join(ret) == b''.join((callback_name.encode('utf8'), b'(', json.dumps({ "i": 42, "s": "foo" }), b');'))
(id(ctx), ctx.call_start)) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) 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(skip_depth=2)) 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', 7789, wsgi_wrapper)
imanageuser.IsAdministrator = True # TODO:需要做在线人数统计 user = json.dumps(imanageuser, default=UserInfo.obj_2_json) user = SecretHelper.AESEncrypt(user) Msg = str(user, encoding = "utf8") else: Msg = "['认证失败']" else: returnStatusCode = '' returnStatusCode, userInfo = LogOnService.UserLogOn(Account, Password, '', False, ctx.transport.req["REMOTE_ADDR"]) if returnStatusCode == StatusCode.statusCodeDic.get('OK'): user = json.dumps(userInfo, default=UserInfo.obj_2_json) user = SecretHelper.AESEncrypt(user) Msg = str(user, encoding="utf8") else: Msg = "['认证失败']" yield Msg login_application = Application([LoginService], tns='Usable-Programming.LoginService.CheckLogin', in_protocol = JsonDocument(validator='soft'), out_protocol=JsonDocument()) login_service = csrf_exempt(DjangoApplication(login_application))
totalCrimes = sum(dict_crimeType.values()) sorted_dict_address = sorted(dict_address.items(), key=operator.itemgetter(1), reverse=True) top_three_dangerous_streets = [] for k, v in sorted_dict_address[:3]: top_three_dangerous_streets.append(k) resp["total_crime"] = totalCrimes resp["the_most_dangerous_streets"] = top_three_dangerous_streets resp["crime_type_count"] = dict_crimeType resp["event_time_count"] = dict_time yield resp application = Application([HelloWorldService], tns='spyne.examples.hello', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument()) if __name__ == '__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. from wsgiref.simple_server import make_server wsgi_app = WsgiApplication(application) server = make_server('0.0.0.0', 8000, wsgi_app) server.serve_forever()
def main(): global protocols rest = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=HttpRpc()) xml = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=XmlDocument()) soap = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=Soap11()) html = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=HtmlMicroFormat()) png = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=PngClock()) svg = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=SvgClock()) json = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument()) jsoni = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument( ignore_wrappers=True)) jsonl = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument(complex_as=list)) jsonil = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=JsonDocument( ignore_wrappers=True, complex_as=list)) msgpack_doc = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=MessagePackDocument()) msgpack_rpc = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=MessagePackRpc()) yaml = Application([MultiProtService], tns=tns, in_protocol=HttpRpc(), out_protocol=YamlDocument()) dyn = Application([DynProtService], tns=tns, in_protocol=HttpRpc(validator='soft'), out_protocol=HttpRpc()) DynProtService.protocols = { 'json': Tsetprot(JsonDocument(dyn)), 'xml': Tsetprot(XmlDocument(dyn)), 'yaml': Tsetprot(YamlDocument(dyn)), 'soap': Tsetprot(Soap11(dyn)), 'html': Tsetprot(HtmlMicroFormat(dyn)), 'png': Tsetprot(PngClock(dyn)), 'svg': Tsetprot(SvgClock(dyn)), 'msgpack': Tsetprot(MessagePackDocument(dyn)), } root = WsgiMounter({ 'rest': rest, 'xml': xml, 'soap': soap, 'html': html, 'png': png, 'svg': svg, 'json': json, 'jsoni': jsoni, 'jsonl': jsonl, 'jsonil': jsonil, 'mpd': msgpack_doc, 'mprpc': msgpack_rpc, 'yaml': yaml, 'dyn': dyn, }) from wsgiref.simple_server import make_server server = make_server(host, port, root) logging.basicConfig(level=logging.DEBUG) logging.info("listening to http://%s:%d" % (host, port)) logging.info("navigate to e.g. http://%s:%d/json2/get_utc_time" % (host, port)) logging.info(" or: http://%s:%d/xml/get_utc_time" % (host, port)) return server.serve_forever()
# * The list of services it should wrap, # * A namespace string. # * An input protocol. # * An output protocol. application = Application( [CheckCrimeService], 'spyne.model.complex.checkcrime', # The input protocol is set as HttpRpc to make our service easy to # call. Input validation via the 'soft' engine is enabled. (which is # actually the the only validation method for HttpRpc.) in_protocol=HttpRpc(validator='soft'), # The ignore_wrappers parameter to JsonDocument simplifies the reponse # dict by skipping outer response structures that are redundant when # the client knows what object to expect. out_protocol=JsonDocument(ignore_wrappers=True), ) # Now that we have our application, we must wrap it inside a transport. # In this case, we use Spyne's standard Wsgi wrapper. Spyne supports # popular Http wrappers like Twisted, Django, Pyramid, etc. as well as # a ZeroMQ (REQ/REP) wrapper. wsgi_application = WsgiApplication(application) # More daemon boilerplate server = make_server('0.0.0.0', 8000, wsgi_application) logging.info("listening to http://0.0.0.0:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server.serve_forever()
def get_object_as_json(o, cls, ignore_wrappers=True, complex_as=list, encoding="utf8"): prot = JsonDocument(ignore_wrappers=ignore_wrappers, complex_as=complex_as) ctx = FakeContext(out_document=[prot._object_to_doc(cls, o)]) prot.create_out_string(ctx, encoding) return "".join(ctx.out_string)