基于协程的异步编程(异步上下文管理器)-5
普通上下文管理器
上下文管理举例来说 比如你想要链接数据,然后自己总忘记关闭连接,就可以使用上下文管理器来实现
可以将获取资源链接放到__enter__中,将资源关闭放到__exit__中。
使用with ContextManager() as f: 就可以自动关闭链接了。实例时会先执行__enter__获取链接,操作完成后,执行__exit__关闭连接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class ContextManager: def __init__(self): self.conn = None def operate(self): print('任何操作。') def __enter__(self): print('链接数据库') return self def __exit__(self, exc_type, exc_val, exc_tb): print("关闭数据库链接") with ContextManager() as f: f.operate() |
异步上下文管理器
异步上下文管理器
异步上下文管理器 使用__aenter__进行链接,必须返回自己本身,f将获取到本身。使用__aexit__进行关闭。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class AsyncContextManager: def __init__(self): self.conn = None async def operate(self): print('任何操作') return 'data' async def __aenter__(self): # 异步链接数据库 print('异步链接数据库') self.conn = await asyncio.sleep(2) return self async def __aexit__(self, exc_type, exc_val, exc_tb): # 异步关闭数据库 print('异步关闭数据库') await asyncio.sleep(2) # 异步上下文管理器 想要使用 必须在异步函数内。 async def run(): async with AsyncContextManager() as f: result = await f.operate() print(result) asyncio.run(run()) |
未经允许不得转载:大师兄 » 基于协程的异步编程(异步上下文管理器)-5
评论已关闭