首页 > 编程语言 >Python 异步上下文管理器

Python 异步上下文管理器

时间:2022-09-24 17:23:31浏览次数:57  
标签:__ 异步 管理器 Python self await conn async def

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"}
关闭链接

 

标签:__,异步,管理器,Python,self,await,conn,async,def
From: https://www.cnblogs.com/ygbh/p/16726033.html

相关文章

  • python-miio库-米家直流变频落地扇1x
    一、先获取tooken原链接:https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor1importbase642importhashlib3importhmac4importjson......
  • Python 异步迭代器
    1、参考来源https://docs.python.org/zh-cn/3.9/reference/datamodel.html?highlight=aiter#asynchronous-iterators2、代码示例:1#-*-coding:utf-8-*-2"""......
  • python 9.24
    classRectangle():defgetperi(self,a,b):return(a+b)*2defgetArea(self,a,b):returna*brect=Rectangle()print(rect.getperi(3,......
  • asyncio与不支持异步的模块结合使用
    1、使用前提将不支持异常的模板与asyncio结合使用【默认是使用线程池+事件循环】2、同时下载3张图片的示例1#-*-coding:utf-8-*-2"""3FileName:te......
  • python解释器下载与安装指导手册
    python解释器下载与安装指导手册1.python解释器1.1下载地址1https://www.python.org/1.2.python解释器下载1.3.python解释器主流版本python2.Xpython2.7是2.......
  • Python使用事件循环创建线程池和进程池
    1、来源参考参考官方文档示例:https://docs.python.org/3.9/library/asyncio-eventloop.html#asyncio.loop.run_in_executor2、代码示例1#-*-coding:utf-8-*-2......
  • Python基础教程,Python入门教程(超详细)
    Python由荷兰数学和计算机科学研究学会于1990年代初设计,作为一门叫做ABC语言的替代品。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应......
  • Python爬取全球疫情数据,制作数据可视化图
    前言开发环境python3.8:解释器pycharm:代码编辑器requests发送请求pyecharts绘制图表pandas读取数据爬虫案例思路流程:一.数据来源分析:......
  • Python中的赋值表达式
    赋值表达式(assignmentexpression)是Python3.8新引入的语法,它会用到海象操作符(walrusoperator)。这种写法可以解决某些持续已久的代码重复问题。a=b是一条普通的赋值语......
  • python爬虫随机headers伪装fake_useragent
    python爬虫随机headers伪装fake_useragentfake_useragent库调用方法ua.random可以随机返回一个headers(User-Agent)fromfake_useragentimportUserAgent#下载:pip......