etayluz
etayluz

Reputation: 16416

Tornado: not making async request

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?

Upvotes: 0

Views: 304

Answers (2)

Ben Darnell
Ben Darnell

Reputation: 22134

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)

Upvotes: 2

Raj Damani
Raj Damani

Reputation: 792

First of all please check are you running your code through python 3.4 ?

Next thing is please check print statement where there is no brackets.

As I have run your code with little changes and it worked.

>>> def handle_response(response):
...     if response.error:
...             print("error: {}".format(response.error))
...     else:
...             print(response.body)
...
>>> http_client = AsyncHTTPClient()
>>> http_client.fetch("https://www.google.com",handle_response)
<tornado.concurrent.Future object at 0x03ADF570>

Upvotes: 1

Related Questions