Python 异步上下文管理器

1、参考来源

https://docs.python.org/zh-cn/3.9/reference/datamodel.html?highlight=aiter#asynchronous-context-managers

2、代码示例

 1 # -*- coding: utf-8 -*-
 2 """
 3    File Name : test
 4    Description :
 5    Author : Administrator
 6 """
 7 import asyncio
 8 
 9 
10 class AsyncContextManager(object):
11     def __init__(self, conn):
12         self.conn = conn
13 
14     async def handler_event(self):
15         print('查询数据')
16         return '{name:"ok"}'
17 
18     async def __aenter__(self):
19         self.conn = await asyncio.sleep(1)  # 模拟网络io
20         return self
21 
22     async def closed(self):
23         print('关闭链接')
24 
25     async def __aexit__(self, exc_type, exc_val, exc_tb):
26         await asyncio.sleep(1)  # 模拟关闭链接的io
27         await self.closed()
28 
29 
30 async def task():
31     async with AsyncContextManager('链接对象') as conn_obj:
32         result = await conn_obj.handler_event()
33         print(result)
34 
35 
36 if __name__ == '__main__':
37     asyncio.run(task())

3、运行结果

查询数据
{name:"ok"}
关闭链接

 

posted @ 2022-09-24 17:10  小粉优化大师  阅读(70)  评论(0编辑  收藏  举报