Package: dizzydecor
dizzydecoris a python library that makes it easy to create web services
in tornado. To accomplish this, the library adds two new classes and decorators
that help eliminate the need for boilerplate code.New in version 0.0.4Support for handler initialization with keyword arguments to thewebservicedecoratorAdded support for path arguments (anything included in the url after the method name is added to a path_args list that will be passed to the called method)Custom service paths (use the path keyword argument in thewebservicedecorator)Custom method names (use the name keyword argument in theservicemethoddecorator)Bypass body parsing on a per-method basis with the ignore_body keyword argument on theservicemethoddecoratorExampleHere is an example to show howdizzydecor, works:fromtornado.ioloopimportIOLoopfromdizzydecorimport(WSApplication,WebserviceHandler,webservice,servicemethod)# The webservice decorator accepts keyword argument that will be used in# the handler's initialize method@webservice(greeting="This is my custom greeting")classMyWebService(WebserviceHandler):definitialize(self,greeting):self.greeting=greeting@servicemethod()asyncdefecho(self,message):returnf"You said:{message}"@servicemethod(httpmethod="GET")asyncdefmy_greeting(self):returndict(greeting="Hello, welcome to my web service demo!")# Use the name argument to setup custom method names# anything included in the url after the method name is sent to the# method in an array named path_args@servicemethod(ignore_body=True,name="greet")asyncdefmy_other_greeting(self,path_args):# with ignore_body set to True, you can parse the body yourselfbody=self.request.body.decode("utf-8")returndict(greeting=self.greeting,body=body,path_args=path_args)# The path argument allows you to configure a custom path for this webservice@webservice(path=r"/custom-name/(.+)")classTotallyNonsensicalName(WebserviceHandler):@servicemethod()asyncdefecho(self,message):returndict(message=message)if__name__=="__main__":app=WSApplication()app.listen(8080)IOLoop.current().start()This will create two web services. The first has three methods: echo, my_greeting, and my_other_greeting.
By default, service methods respond to POST requests; however, thehttpmethodargument toservicemethodcan change this behaviour. For instance,
my_greeting is setup to respond to GET requests.Paths are generated based on class and method names.A web service’s path is the lower-case class name with each word joined by a hyphen. (MyWebService -> my-web-service)A method’s path is the method’s name with underscores replaced with hyphens. (my_greeting -> my-greeting)Paths can also be configured manually.Thepathargument can be used with thewebservicedecorator to configure the web service’s base pathMethod names can be configured with theservicemethoddecorator’snameargumentIf a service method does not get all of its arguments, the service handler sends a 400 HTTP status code automatically.To test, you can use curl:$ curl http://localhost:8080/my-web-service/echo -d '{"message": "This is my message"}'
"You said: This is my message"

$ curl http://localhost:8080/my-web-service/my-greeting
{"greeting": "Hello, welcome to my web service demo!"}

$ curl -d '{"a": 1}' http://localhost:8080/my-web-service/greet/t
{"greeting": "This is my custom greeting", "body": "{\"a\": 1}", "path_args": ["t"]}

$ curl -d '{"message": "test"}' http://localhost:8080/custom-name/echo
{"message": "test"}

$ curl -d '{"messag": "test"}' http://localhost:8080/custom-name/echo
"<html><title>400: Bad Request</title><body>400: Bad Request</body></html>"You may have noticed that the example uses JSON.What if I do not want to use JSON?In this case, all you need to do is override theloadanddumpmethods in a subclass ofWebserviceHandlerorSyncWebserviceHandlerHere is an example withPyYAML:# -- snip --importyamlclassYAMLServiceHandler(WebserviceHandler):defload(self,request):returnyaml.safe_load(request)defdump(self,response):# You can also set content-type here with self.set_headerreturnyaml.safe_dump(response)@webservice()classYetAnotherService(YAMLServiceHandler):@servicemethod()asyncdefjoin(self,arr,delim):returndict(message=delim.join(map(str,arr)))# -- snip --The rest is exactly the same, except now your service will use YAML.Here’s how to test it with curl:$ curl http://localhost:8080/yet-another-service/join --data-binary @"/dev/stdin"<<_eof_
arr:
    - Hello
    - world
delim: " "
_eof_
message: Hello worldInstallationInstall with pip or easy_install:$ pip install dizzydecordizzydecoris only available for Python 3What about non-standard HTTP methods? (Experimental)In this case, all you need to do is extend the SUPPORTED_METHODS property
of the service handler class.# -- snip --@webservice()classNotificationService(WebserviceHandler):SUPPORTED_METHODS=WebserviceHandler.SUPPORTED_METHODS+("NOTIFY",)@servicemethod(httpmethod="NOTIFY")asyncdefnotification(self,message):# etc# -- snip --The script for the new HTTP method is added to the service handler
during the creation of the web service. After that, all you need to
do is setup to service method to respond to that request type. Depending
on the situation, you might also need to customize the way arguments are
parsed by overriding prepare.What if I want to use a custom tornado request handler?If you want to add a handler that does not fit the web service mold, you can append it to the WSApplication’s endpoints class variable.
For example, maybe you want to add a websocket:ws_clients=[]msg_buffer=[]classEchoWebSocket(WebSocketHandler):defopen(self):print("WebSocket opened")ws_clients.append(self)formsginmsg_buffer:self.write_message(msg)defon_message(self,message):globalmsg_buffermessage=u"Someone said: "+messagemsg_buffer=msg_buffer[:19]msg_buffer.append(message)forclientinws_clients:client.write_message(message)defon_close(self):print("WebSocket closed")ws_clients.remove(self)defcheck_origin(self,origin):returnTrueif__name__=="__main__":WSApplication.endpoints.append((r"/websocket",EchoWebSocket))# The keyword arguments websocket_ping_interval and websocket_ping_timeout# are passed to the underlying Application classapp=WSApplication(websocket_ping_interval=3,websocket_ping_timeout=5)app.listen(8080)IOLoop.current().start()Any web services you added with dizzydecor decorators will still work.Synchronous servicesTheWebserviceHandleris asynchronous; however, you can make synchronous
service handlers using theSyncWebserviceHandlerclass.# -- snip --@webservice()classMySyncService(SyncWebserviceHandler):# This time the method is not async@servicemethod(httpmethod="GET")defmy_greeting(self):returndict(greeting="Hello...")# -- snip --