1

我在交互式 python 解释器中输入了来自 tornado 网站的AsyncHTTPClient示例代码,但异步 HTTP 请求从未执行。

def handle_request(response):
    if response.error:
        print "Error:", response.error
    else:
        print response.body

http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_request)

# handle_request function is never executed (nothing is printed)

我可以使用AsyncHTTPClientnot 作为 Web 服务器处理的一部分吗?

4

1 回答 1

3

是的,但是您应该启动一个IOLoop,例如docs

from tornado import ioloop
from tornado.httpclient import AsyncHTTPClient


def handle_request(response):
    if response.error:
        print "Error:", response.error
    else:
        print response.body
    ioloop.IOLoop.instance().stop()

http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_request)
ioloop.IOLoop.instance().start()
于 2013-09-14T13:03:00.757 回答