Tornado is a non-blocking I/O web server. In Tornado, when the request handler serves the request made by the client, the request is closed by itself. Python decorator @tornado.web.asynchronous can be used to override the default behavior (of automatically finishing the request) and keep the request open. So, its the duty of the server developer to finish the request.
Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tornado.ioloop | |
import tornado.web | |
import httplib2 | |
httplib2.debuglevel=1 | |
http = httplib2.Http() | |
class AsyncHandler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(self): | |
self.response, self.content = http.request("http://google.co.in", "GET") | |
self._async_callback(self.response) | |
def _async_callback(self, response): | |
print response.keys() | |
self.finish() | |
tornado.ioloop.IOLoop.instance().stop() | |
application = tornado.web.Application([ | |
(r"/", AsyncHandler)], debug=True) | |
if __name__ == "__main__": | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
In the above example, When user browses to http://127.0.0.1/, AsyncHandler handles it and sends a GET request to http://google.co.in and receives the response. Processing of this response is done by _async_callback() method. Thus in this example, when get() returns, the request has not been finished. Once the response is processed and self.finish() is called, only then request is completed.
If the developer fails to finish the request with self.finish(), the browser hangs as in the picture below.
Hello!
Is possible to use Tornado with httplib2 module?
Your code doesn’t work on Win Server 2003.
Hi edisam,
1. Tornado’s ioloop doesn’t support Win file descriptors; it supports epoll and kqueue, that’s unavailable on Windows.
2. “Is possible to use Tornado with httplib2 module?” – didn’t get the essence of the question? Isn’t this example using httplib2 to make requests, response of which are handled by Tornado async callback?
httplib2 will block the tornado loop, you can use tornado.httpclient