简体   繁体   English

如何调试龙卷风异步操作

[英]how to debug Tornado async operation

I am new to Tornado framework, and according to the link Asynchronous and non-Blocking I/O , I wrote some demo code as below. 我是Tornado框架的新手,根据异步和非阻塞I / O链接 ,我编写了一些演示代码,如下所示。 Unfortunately, the sync http client works, but async http client not. 不幸的是,同步http客户端有效,但异步http客户端无效。 It looks like, the callback function that I passed to AsyncHTTPClient.fetch never has the chance to run. 看来,我传递给AsyncHTTPClient.fetch的回调函数从来没有机会运行。 So my question is: 所以我的问题是:

  • Why tornado's async API not work for me? 为什么龙卷风的异步API对我不起作用?
  • How should I debug this kind of problem? 我应该如何调试此类问题? Set a break-point to my callback function is useless because it never has chance to run. 为我的回调函数设置断点是没有用的,因为它永远不会运行。

Any help is great appreciated. 任何帮助都非常感谢。 Below is my demo code: 下面是我的演示代码:

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!")

You need to start the IOLoop, otherwise your asynchronous task never makes progress: 您需要启动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()

In this example I stop the loop at the bottom of printResponse. 在此示例中,我将循环停在printResponse的底部。 In a real web server application you might never explicitly stop the loop. 在实际的Web服务器应用程序中,您可能永远不会明确停止循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM