【协程】10、异步上下文管理器

1、异步上下文管理器

  • 此种对象通过定义__aenter__()和__aexit__()方法来对async with语句中的环境进行控制。
import asyncio

class AsyncContextManage:
    def __init__(self):
        self.conn = conn
    
    async def do_something(self):
        # 异步操作数据库
        return 666
    
    async def __aenter__(self):
        # 异步链接数据库
        self.conn = await asyncio.sleep(a)
        return self
    
    async def __aexit__(self, exc_type, exc, tb):
        # 异步关闭数据库链接
        await asyncio.sleep(1)
async def func():
    async with AsyncContextManage() as f:
        result = await f.do_something()
        print(result)
asyncio.run(func())
posted @ 2022-05-31 14:10  郭祺迦  阅读(55)  评论(0)    收藏  举报