无法在龙卷风上调用result()
我想使用python库龙卷风(版本4.2)进行一些异步HTTP请求。但是,result()
由于出现异常:我无法强迫将来完成(使用),因为“
DummyFuture不支持阻止结果”。
我有python 3.4.3,因此将来的支持应该成为标准库的一部分。的文档concurrent.py
说:
concurrent.futures.Future
如果有龙卷风,将使用。否则,它将使用此模块中定义的兼容类。
下面提供了我尝试做的一个最小示例:
from tornado.httpclient import AsyncHTTPClient;
future = AsyncHTTPClient().fetch("http://google.com")
future.result()
如果我正确理解我的问题,则会发生此问题,因为concurrent.futures.Future
未使用某种方式的导入。龙卷风中的相关代码似乎在其中,concurrent.py
但是我在理解问题的根源方面并没有真正取得进展。
-
尝试创建另一个
Future
并使用add_done_callback
:from tornado.concurrent import Future def async_fetch_future(url): http_client = AsyncHTTPClient() my_future = Future() fetch_future = http_client.fetch(url) fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_future
但是您仍然需要 使用ioloop解决未来 ,例如:
# -*- coding: utf-8 -*- from tornado.concurrent import Future from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop def async_fetch_future(): http_client = AsyncHTTPClient() my_future = Future() fetch_future = http_client.fetch('http://www.google.com') fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_future response = IOLoop.current().run_sync(async_fetch_future) print(response.body)
另一种方法是使用
tornado.gen.coroutine
装饰器,如下所示:# -*- coding: utf-8 -*- from tornado.gen import coroutine from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop @coroutine def async_fetch_future(): http_client = AsyncHTTPClient() fetch_result = yield http_client.fetch('http://www.google.com') return fetch_result result = IOLoop.current().run_sync(async_fetch_future) print(result.body)
coroutine
装饰器使函数返回Future
。