龙卷风不能正确产生期货

Tornado doesnt yield futures correctly

我需要在 tornado 请求处理程序中异步进行多个 http 调用。

尝试 return 期货没有很好的记录并且几乎不可能在龙卷风处理程序级别的聚集 asyncio.gather 上完成。

我已经尝试过 aiohttp,它本身可以正常工作,但是当把它放在龙卷风处理程序中时,它会抛出 loop is already in use。如果你能告诉我如何向 IOLoop 注入一些新的 futures 来解决那会很好。

我也尝试过使用 tornados AsyncHTTPClient,与文档相反,它实际上并没有使用 yield,而是 return 当您在其上使用 await 时的响应。

是否有关于此的最新文档?所有示例不适用于多个异步请求。

根据此文档http://www.tornadoweb.org/en/stable/gen.html#module-tornado.gen

@gen.coroutine
def get(self):
    http_client = AsyncHTTPClient()
     response1, response2 = yield [http_client.fetch(url1),
                              http_client.fetch(url2)]
    response_dict = yield dict(response3=http_client.fetch(url3),
                           response4=http_client.fetch(url4))
    response3 = response_dict['response3']
    response4 = response_dict['response4']

然而,当我自己尝试这样做时,yield 会抛出一个错误,将其替换为 await 会得到一个结果。但是你不能像 yield 那样等待一个 dict 对象。我该如何解决这个问题?

python 3.6.7 龙卷风5.1.1 aiohttp 3.5.4

您的评论使用了 await 这个词,所以听起来您 运行 了解原生协程(使用 async defawait 定义)之间的区别和修饰协程(用 @gen.coroutineyield 定义)。您只能 yield 列表和字典直接在修饰的协程中。

在原生协程中,必须使用tornado.gen.multi(或asyncio.gather):

async def get(self):
    http_client = AsyncHTTPClient()
    response1, response2 = await gen.multi([http_client.fetch(url1),
                                            http_client.fetch(url2)])
    response_dict = await gen.multi(dict(response3=http_client.fetch(url3),
                                         response4=http_client.fetch(url4)))
    response3 = response_dict['response3']
    response4 = response_dict['response4']

记录了两种协程风格的区别here