我是Tornado框架的新手,根据链接Asynchronous and non-Blocking I/O,我写了一些演示代码,如下所示。不幸的是,同步http客户端工作,但async http客户端没有。看起来,我传递给AsyncHTTPClient.fetch的回调函数永远不会有机会运行。所以我的问题是:
非常感谢任何帮助。以下是我的演示代码:
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPClient
import time
myUrl = 'a http url serving RESTful service'
def async_fetch(url, callback):
http_client = AsyncHTTPClient()
def handle_test(response):
callback(response.body)
http_client.fetch(url, handle_test)
def sync_fetch(url):
http_client = HTTPClient()
response = http_client.fetch(url)
return response.body
def printResponse(data):
print("response is:" + data)
def main():
sync_fetch(myUrl) #this works
async_fetch(myUrl, printResponse) #this not work
if __name__ == '__main__':
main()
print("begin of sleep!")
time.sleep(2)
print("end of sleep!")
答案 0 :(得分:1)
您需要启动IOLoop,否则您的异步任务永远不会取得进展:
from tornado.ioloop import IOLoop
def printResponse(data):
print("response is:" + data)
IOLoop.current().stop()
def main():
sync_fetch(myUrl) #this works
async_fetch(myUrl, printResponse)
IOLoop.current().start()
在这个例子中,我停止了printResponse底部的循环。在真实的Web服务器应用程序中,您可能从不明确地停止循环。