Python 向异步上下文管理器添加超时

Python 向异步上下文管理器添加超时,python,python-asyncio,Python,Python Asyncio,Python很有用,但它们与 向异步上下文管理器添加超时的最佳方法是什么 向异步上下文管理器添加超时的最佳方法是什么 您不能将wait\u for应用于异步上下文管理器,但可以将其应用于使用它的协同程序。因此,要向上下文管理器添加超时,请在异步函数中使用它,并对其应用超时。例如: async def download(url, session): async with session.get(url) as resp: return await resp.text()

Python很有用,但它们与

向异步上下文管理器添加超时的最佳方法是什么

向异步上下文管理器添加超时的最佳方法是什么

您不能将
wait\u for
应用于异步上下文管理器,但可以将其应用于使用它的协同程序。因此,要向上下文管理器添加超时,请在异步函数中使用它,并对其应用超时。例如:

async def download(url, session):
    async with session.get(url) as resp:
        return await resp.text()

async def print_google(session):
    try:
        text = await asyncio.wait_for(download('http://www.google.com', session), 1)
    except asyncio.TimeoutError:
        text = None
    print(text)
你试过了吗?只需将任何异步代码(包括异步上下文管理器的使用)包装为
async with timeout()

如果只想将超时应用于异步上下文管理器,则可以创建利用
异步超时的新上下文管理器

import asyncio
from contextlib import asynccontextmanager

from async_timeout import timeout


@asynccontextmanager
async def my_acm():
    print('before')
    yield
    print('after')


async def main():
    async with timeout(1):
        async with my_acm():
            await asyncio.sleep(1.5)


asyncio.run(main())
import asyncio
from contextlib import asynccontextmanager

from async_timeout import timeout


@asynccontextmanager
async def my_acm():
    print('before')
    yield
    print('after')


@asynccontextmanager
async def my_acm_plus_timeout(time):
    async with timeout(time):
        async with my_acm():
            yield


async def main():
    async with my_acm_plus_timeout(1):
        await asyncio.sleep(1.5)


asyncio.run(main())