本文介绍了我可以使用asyncio.wait_for()作为上下文管理器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不起作用:

  try:
与asyncio.wait_for(aiohttp.get( url),2)as resp:
print(resp.text())
除了asyncio.TimeoutError如e:
pass

送礼

 与asyncio.wait_for(aiohttp.get( url),2)as resp:
AttributeError:__aexit__

据我了解, asyncio.wait_for()将超过 aiohttp.get()的未来,后者具有 __ aenter__ __ aexit __ 方法(事实证明与aiohttp.get()async异步) >作品)。

解决方案

您不能使用wait_for(...) async $ c>- wait_for 不支持异步上下文管理器。



我将添加将超时类设置为 asyncio 很快-请参见对话。



现在您可以尝试 aiohttp.Timeout (尽管它需要安装足够胖的软件包)-或仅复制这40行代码。



有趣的是:这种方法不需要异步-仅使用具有$code>的旧商品就足够了。 / p>

UPD 我想念您已经使用aiohttp了。
因此,请遵循中的第二个示例。


Why wouldn't this work:

try:
    async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
        print(resp.text())
except asyncio.TimeoutError as e:
    pass

Gives

async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
AttributeError: __aexit__

To my understanding, asyncio.wait_for() would pass the future of aiohttp.get(), which has an __aenter__ and __aexit__ method (as is demonstrated by the fact that async with aiohttp.get() works).

解决方案

You cannot write async with wait_for(...) -- wait_for doesn't support asynchronous context manager.

I'll add Timeout class to asyncio soon -- see https://groups.google.com/forum/#!topic/python-tulip/aRc3VBIXyRc conversation.

For now you can try aiohttp.Timeout (it requires installing a fat enough package though) -- or just copy these 40 lines of code.

Interesting thing: the approach doesn't require async with -- just old good with is enough.

UPD I missed that you use aiohttp already.Thus just follow the second example from aiohttp timeouts chapter.

这篇关于我可以使用asyncio.wait_for()作为上下文管理器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 10:58