In this tutorial, we will introduce how to implement tornado asynchronous execution for GET and POST request. It is very useful for us to increase the performance of the tornado web server.
We usually build a web server using tornado as follows:
import tornado from tornado.web import RequestHandler class ChexianVoiceprintHandler_V2(RequestHandler): def get(self, *args, **kwargs): pass def post(self, *args, **kwargs): # do something, for example: create voiceprint result = do() self.write(result) def make_app(): setting = dict( ) return tornado.web.Application( [(r'/ChexianVoiceprintRequest_V2', ChexianVoiceprintHandler_V2)] ) if __name__ == '__main__': app = make_app() app.listen(9003) tornado.ioloop.IOLoop.current().start()
However, it is not asynchronous.
In order to implement tornado asynchronous execution, we should use @gen.coroutine. Here is an example:
import tornado from tornado import gen from tornado.web import RequestHandler class ChexianVoiceprintHandler_V2(RequestHandler): def get(self, *args, **kwargs): pass @gen.coroutine def post(self): future = tornado.concurrent.Future() future.add_done_callback(self.do_simple()) yield future def do_simple(self, *args, **kwargs): # do something, for example: create voiceprint result = do() self.write(result) self.finish() def make_app(): setting = dict( ) return tornado.web.Application( [(r'/ChexianVoiceprintRequest_V2', ChexianVoiceprintHandler_V2)] ) if __name__ == '__main__': app = make_app() app.listen(9003) tornado.ioloop.IOLoop.current().start()
As to this example, we should return a future object and finish it manually.