I'm a newbie to Tornado and I'm trying to use it to make an async call as in the documentation:
from tornado.httpclient import AsyncHTTPClient
def handle_response(response):
"""Handles response"""
print 'here'
if response.error:
print "Error:", response.error
else:
print response.body
http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_response)
When I run this program nothing is printed :(
The program just runs and exits. What am I doing wrong?
You have to start the IOLoop for asynchronous stuff to run. The last line of a tornado program is typically tornado.ioloop.IOLoop.current().start()
. You'd then call IOLoop.current().stop()
in handle_response
, assuming this one request is all you want to do.
Another way to start and stop the IOLoop for a single function is like this: response = IOLoop.current().run_sync(functools.partial(http_client.fetch, url))
(and then you'd handle the response afterwards)