2017-04-10 136 views
0

我是一个新手,Tornado,我想用它做一个异步调用作为documentation龙卷风:不进行异步请求

from tornado.httpclient import AsyncHTTPClient 

def handle_response(response): 
    """Handles response""" 
    print 'here' 
    if response.error: 
     print "Error:", response.error 
    else: 
     print response.body 

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

当我运行这个程序没有打印: (

程序只运行和退出。 我在做什么错?

+0

我希望我的回答是,你在找什么! –

回答

2

您必须启动IOLoop才能运行异步内容。龙卷风计划的最后一行通常是tornado.ioloop.IOLoop.current().start()。然后,您将在handle_response中拨打IOLoop.current().stop(),假设您只需要这一个请求。

另一种方式来启动和停止IOLoop单个功能是这样的:response = IOLoop.current().run_sync(functools.partial(http_client.fetch, url))(然后你事后处理响应)

+0

这听起来不错,但我收到此错误:NameError:名称'龙卷风'未定义 – etayluz

+0

关于第二种方法,我正在寻找一种异步方法。我是从node.js进入Python的 - 这似乎是一种非常不同的思维和编码方式。 – etayluz

+0

看起来像这是必要的:import tornado.ioloop – etayluz

1

首先,请你通过python的运行代码3.4?

接下来的事情是请检查打印语句哪里没有括号。

因为我已经运行你的代码,几乎没有变化,它的工作。

>>> def handle_response(response): 
...  if response.error: 
...    print("error: {}".format(response.error)) 
...  else: 
...    print(response.body) 
... 
>>> http_client = AsyncHTTPClient() 
>>> http_client.fetch("https://www.google.com",handle_response) 
<tornado.concurrent.Future object at 0x03ADF570> 
+0

谢谢,但它不是我正在寻找 – etayluz