Wil*_*lem 3 python-3.x python-asyncio aiohttp
为什么这行不通:
try:
async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
print(resp.text())
except asyncio.TimeoutError as e:
pass
Run Code Online (Sandbox Code Playgroud)
给
async with asyncio.wait_for(aiohttp.get(url), 2) as resp:
AttributeError: __aexit__
Run Code Online (Sandbox Code Playgroud)
据我了解,asyncio.wait_for()将传递 , 的未来aiohttp.get(),它有一个__aenter__and__aexit__方法(正如有效的事实所证明的那样async with aiohttp.get())。
你不能写async with wait_for(...)——wait_for不支持异步上下文管理器。
我很快就会添加Timeout课程asyncio- 请参阅https://groups.google.com/forum/#!topic/python-tulip/aRc3VBIXyRc对话。
现在你可以尝试aiohttp.Timeout(尽管它需要安装一个足够大的包)——或者只是复制这 40 行代码。
有趣的事情:该方法不需要async with- 只要旧的with就足够了。
UPD我错过了你已经使用 aiohttp 了。因此,只需遵循aiohttp 超时章节中的第二个示例。