Loading

7.异步上下文管理器

对象通过定义__aenter__()和__aexit__()方法对async with语句进行控制

class AsyncConetxtManager:
    def __init__(self):
        self.conn = ''

    async def do_something(self):
        return '异步操作数据'

    async def __aenter__(self):
        # '异步连接数据库'
        self.conn = '连击数据库'
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        # 异步关闭数据库连接
        await asyncio.sleep(1)


async  def func():
    #  async with必须在协程函数内
    async with AsyncConetxtManager() as f:
        r = await f.do_something()
        print(r)
asyncio.run(func())

 

posted @ 2022-08-21 22:57  木子七  阅读(28)  评论(0编辑  收藏  举报