我可以使用 asyncio.wait_for() 作为上下文管理器吗?

Can I use asyncio.wait_for() as a context manager?

为什么这行不通:

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

给予

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

根据我的理解,asyncio.wait_for() 将传递 aiohttp.get() 的未来,它有一个 __aenter____aexit__ 方法(正如 async with aiohttp.get() 有效)。

你不能写 async with wait_for(...) -- wait_for 不支持异步上下文管理器。

我会尽快将 Timeout class 添加到 asyncio -- 查看 https://groups.google.com/forum/#!topic/python-tulip/aRc3VBIXyRc 对话。

现在您可以尝试 aiohttp.Timeout(尽管它需要安装足够大的包)——或者只复制这 40 行代码。

有趣的是:该方法不需要 async with -- 只需旧的 with 就足够了。

UPD 我想念你已经在使用 aiohttp 了。 因此,只需按照 aiohttp timeouts chapter.

中的第二个示例