龙卷风:不发出异步请求

Tornado: not making async request

我是 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)

当我运行这个程序什么都不打印时:(

程序刚 运行s 就退出了。 我做错了什么?

首先请检查您是否运行通过 python 3.4 更新您的代码?

接下来请检查没有括号的打印语句。

因为我有运行你的代码,稍作改动就可以了。

>>> 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>

您必须启动用于异步内容的 IOLoop 到 运行。 tornado 程序的最后一行通常是 tornado.ioloop.IOLoop.current().start()。然后,您将在 handle_response 中调用 IOLoop.current().stop(),假设您只想执行此请求。

另一种启动和停止单个函数的 IOLoop 的方法是这样的:response = IOLoop.current().run_sync(functools.partial(http_client.fetch, url))(然后你会处理响应)