[英]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.