问题描述
我想使用 python 库 tornado(4.2 版)执行一些异步 HTTP 请求.但是我不能强制未来完成(使用 result()
),因为我得到一个异常:DummyFuture 不支持结果阻塞".
I want to do some asynchronous HTTP-requests using the python library tornado (version 4.2). I can however not force a future to complete (using result()
) since I get an Exception: "DummyFuture does not support blocking for results".
我有 python 3.4.3,因此未来的支持应该是标准库的一部分.concurrent.py
的文档说:
I have python 3.4.3 therefore future support should be part of the standard library. The documentation of concurrent.py
says:
Tornado 将使用 concurrent.futures.Future
(如果可用);否则它将使用在此模块中定义的兼容类.
下面提供了我正在尝试做的最小示例:
A minimal example for what I am trying to do is provided below:
from tornado.httpclient import AsyncHTTPClient;
future = AsyncHTTPClient().fetch("http://google.com")
future.result()
如果我正确理解我的问题,它会发生,因为以某种方式没有使用 concurrent.futures.Future
的导入.tornado 中的相关代码似乎在 concurrent.py
中,但我在理解问题究竟出在哪里方面并没有真正取得进展.
If I understand my problem correctly it occurs because the import of concurrent.futures.Future
somehow is not used. The relevant code in tornado appears to be in concurrent.py
but I am not really making progress on understanding where exactly the problem lies.
推荐答案
尝试创建另一个Future
并使用add_done_callback
:
Try to create another Future
and use 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解决未来,就像这样:
But you still need solve the future with the ioloop, like this:
# -*- 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
装饰器,如下所示:
Another way to this, is using tornado.gen.coroutine
decorator, like this:
# -*- 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
.
coroutine
decorator causes the function to return a Future
.
这篇关于无法在龙卷风中对期货调用 result()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!