[英]how to debug Tornado async operation
我是Tornado框架的新手,根据异步和非阻塞I / O链接 ,我编写了一些演示代码,如下所示。 不幸的是,同步http客户端有效,但异步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!")
您需要启动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服务器应用程序中,您可能永远不会明确停止循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.