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

爷,独闯天下 提交于 2020-01-14 14:21:47

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/34693678/can-i-use-asyncio-wait-for-as-a-context-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!