【协程】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())本文来自博客园,作者:郭祺迦,转载请注明原文链接:https://www.cnblogs.com/guojie-guojie/p/16330266.html

浙公网安备 33010602011771号