Asynchronous generators

Another way to write asynchronous code in Tornado is by using coroutines. Instead of using a callback function for processing the response, we can use the yield keyword to resume and suspend the execution. Tornado 2.1 introduced the tornado.gen.coroutine module, which provides a pattern for performing asynchronous requests.

You can find the following code in the tornado_request_async_coroutine.py file:

#!/usr/bin/python3

import tornado.ioloop
import tornado.web
import tornado.httpclient

class Handler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
http_client = tornado.httpclient.AsyncHTTPClient()
response = yield tornado.gen.Task(http_client.fetch, "https://www.google.com/search?q=python")
self.write(response.body)

In the previous code block, we define our Handler class that extends from tornado.web.RequestHandler. This class contains the asynchronous get() method and write body response when getting a response from the http_client object.

In the next code block, we define our main program, where we define the event loop and our application managed by the Handler class:

if __name__ == '__main__':
app = tornado.web.Application([tornado.web.url(r"/", Handler)])
app.listen(8080)
tornado.ioloop.IOLoop.current().start()

As you can see, this code is identical to the previous version of the code. The main difference is in how we call the fetch method of the AsyncHTTPClient object.

In the example in the Asynchronous generators section, we will be using Python's yield keyword, which returns control of the program to Tornado, allowing it to execute other tasks while the HTTP request is in progress. When the task is completed, this instruction returns the HTTP response in the request handler and the code is easier to understand.

Note the use of the @tornado.gen.coroutine decorator just before the definition of the get method. This decorator allows Tornado to use internally the tornado.gen.Task class. For more details, you can look over the module documentation, which can be found at http://www.tornadoweb.org/en/stable/gen.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset