异步编程&协程
异步编程&协程
为什么学习协程:
异步相关话题和框架越来越多,例如:tornado、fastapi、django 3.x asgi 、aiohttp都在异步 -> 提升性能。
1.协程
协程不是计算机提供的,是程序员人为创造的。
协程(Coroutine),也被称之为微线程,是一种用户态内的上下文切换技术。简而言之,就是通过一个线程实现代码块相互执行。例如
def func1(): print(1) ... print(2) def func2(): print(3) ... print(4) func1() #常规的调用执行 func2()
实现协程的方法:
-
greenlet,早期模块
-
yield 关键字
-
asyncio 装饰器(python3.4 之后)
-
async、await关键字(py3.5之后)【推荐使用】
1.1 greenlet
pip install greenlet
from greenlet import greenlet def func1(): print(1) # 第2步:输出 1 gr2.switch() # 第3步:切换到 func2 函数 print(2) # 第6步:输出 2 gr2.switch() # 第7步:切换到 func2 函数,从上一次执行的位置继续向后执行 def func2(): print(3) # 第4步:输出 3 gr1.switch() # 第5步:切换到 func1 函数,从上一次执行的位置继续向后执行 print(4) # 第8步:输出 4 gr1 = greenlet(func1) gr2 = greenlet(func2) gr1.switch() # 第1步:去执行 func1 函数
1.2 yield关键字
def func1(): yield 1 yield from func2() yield 2 def func2(): yield 3 yield 4 f1 = func1() for item in f1: print(item)
1.3 asyncio
在python3.4及之后的版本。
import asyncio @asyncio.coroutine def func1(): print(1) # 网络IO请求:下载一张图片 yield from asyncio.sleep(2) # 遇到IO耗时操作,自动化切换到tasks中的其他任务 print(2) @asyncio.coroutine def func2(): print(3) # 网络IO请求:下载一张图片 yield from asyncio.sleep(2) # 遇到IO耗时操作,自动化切换到tasks中的其他任务 print(4) tasks = [ asyncio.ensure_future( func1() ), asyncio.ensure_future( func2() ) ] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks))# 随机选择一个开始执行
注意:遇到IO阻塞自动切换
代码存在弃用的表示coroutine
正常运行,提示关键在在 Python3.8 之后已经弃用,请使用关键字进行替代。
1.4 async & await关键字
在python3.5及之后的版本。
import asyncio async def func1(): print(1) # 网络IO请求:下载一张图片 await asyncio.sleep(2) # 遇到IO耗时操作,自动化切换到tasks中的其他任务 print(2) async def func2(): print(3) # 网络IO请求:下载一张图片 await asyncio.sleep(2) # 遇到IO耗时操作,自动化切换到tasks中的其他任务 print(4) tasks = [ asyncio.ensure_future( func1() ), asyncio.ensure_future( func2() ) ] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks))
2.协程的意义
在一个线程中如果遇到IO等待时间,线程不会傻傻等,利用空闲的时候再去干点其他事。
案例:去下载三张图片(网络IO)。
-
普通方式(同步)
""" pip3 install requests """ import requests def download_image(url): print("开始下载:",url) # 发送网络请求,下载图片 response = requests.get(url) print("下载完成") # 图片保存到本地文件 file_name = url.rsplit('_')[-1] with open(file_name, mode='wb') as file_object: file_object.write(response.content) if __name__ == '__main__': url_list = [ 'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg', 'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg', 'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg' ] for item in url_list: download_image(item) -
协程方式(异步)
import aiohttp import asyncio async def fetch(session, url): print("发送请求:", url) async with session.get(url, verify_ssl=False) as response: content = await response.content.read() file_name = url.rsplit('_')[-1] with open(file_name, mode='wb') as file_object: file_object.write(content) print('下载完成',url) async def main(): async with aiohttp.ClientSession() as session: url_list = [ 'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg', 'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg', 'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg' ] tasks = [ asyncio.create_task(fetch(session, url)) for url in url_list ] await asyncio.wait(tasks) if __name__ == '__main__': asyncio.run( main() )
协程的意义:协程一般应用在有 IO 操作的程序中,因为协程可以利用 IO 等待的时间去执行一些其他的任务,从而提升代码的执行效率。
生活中不也是这样的么,假设 你是一家制造汽车的老板,员工点击设备的【开始】按钮之后,在设备前需等待30分钟,然后点击【结束】按钮,此时作为老板的你一定希望这个员工在等待的那30分钟的时间去做点其他的工作。
3.异步编程
基于async
& await
关键字的协程可以实现异步编程,这也是目前python异步相关的主流技术。
想要真正的了解Python中内置的异步编程,根据下文的顺序一点点来看。
3.1 事件循环
概述:事件循环,可以把他当做一个 while 循环,这个 while 循环在周期性的运行并执行一些任务,在特定条件下终止循环。
# 伪代码 任务列表 = [ 任务1, 任务2, 任务3,... ] while True: 可执行的任务列表,已完成的任务列表 = 去任务列表中检查所有的任务,将'可执行'和'已完成'的任务返回 for 就绪任务 in 已准备就绪的任务列表: 执行已就绪的任务 for 已完成的任务 in 已完成的任务列表: 在任务列表中移除 已完成的任务 如果 任务列表 中的任务都已完成,则终止循环
Python 中创建事件循环的语法如下:
# 创建事件循环 import asyncio loop = asyncio.get_event_loop()
3.2 协程和异步编程
协程函数:定义关键字async def
修饰的函数。
协程对象:调用协程函数返回的对象。
# 定义协程函数 async def func(): pass # 调用协程函数,返回一个协程对象。 result = func()
注意:调用协程函数时,函数内部不会执行,只会返回一个协程对象。
3.2.1 基本应用
程序中需要执行协程函数的内部代码,需要事件循环
和协程对象
配合才能实现,如:
# 定义协程函数并执行 import asyncio async def func(): print("协程函数内部代码") # 只返回协程对象 result = func() # 方式一创建事件循环进行执行 # 1.创建事件循环对象 loop = asyncio.get_event_loop() # 2.将协程对象提交到事件循环的任务列表中,协程执行完才会终止 loop.run_until_complete(result)
import asyncio async def func(): print("协程函数内部代码") # 只返回协程对象 result = func() print("**************8") # 方式二:直接调用内部封装好的函数,函数内部执行的也是上述的相关流程 asyncio.run(result)
注意:run()
方法的使用虽然简便,但是对 Python 版本有相关的要求,必须在python 3.7
以后的版本才能使用改方法。
总结:这个过程可以简单理解为,将协程
当做任务添加到事件循环
列表中,然后事件循环检测列表中的协程
是否为就绪状态(默认可理解为就绪状态),如果准备就绪则执行其内部代码。
3.2.2 await 关键字
await 后面的要求: 可等待的对象(协程对象、Future、Task对象 -> IO等待)
await 是一个只能在协程函数中使用的关键字,用于遇到 IO 操作挂起当前协程(任务),当前协程(任务)挂起过程中, 事件循环可以去执行其他的协程(任务),当前协程的 IO 处理完成时,可以再次切换回来执行 await 之后的代码。
示例1
# await 关键字 import asyncio async def func(): print("执行协程函数的内部代码。") # 遇到IO 操作的时候,挂起当前协程(任务),等待IO操作完成之后在继续向下执行 # 当前协程挂起时,事件循环可以去执行其他协程任务 response = await asyncio.sleep(2) print("IO 请求结束,结果为:",response) asyncio.run(func())
示例2
# await 关键字 import asyncio import time start = time.time() async def other(): print("start") await asyncio.sleep(2) print("end") return "啊哈哈哈哈哈" async def func(): print("执行协程函数的内部代码。") # 遇到IO 操作的时候,挂起当前协程(任务),等待IO操作完成之后在继续向下执行 # 当前协程挂起时,事件循环可以去执行其他协程任务 response = await other() print("IO 请求结束,结果为:",response) asyncio.run(func()) print("运行时间:",time.time()-start)
示例3
# await 关键字 import asyncio import time start = time.time() async def other(): print("start") await asyncio.sleep(2) print("end") return "啊哈哈哈哈哈" async def func(): print("执行协程函数的内部代码。") # 遇到IO 操作的时候,挂起当前协程(任务),等待IO操作完成之后在继续向下执行 # 当前协程挂起时,事件循环可以去执行其他协程任务 response1 = await other() print("IO 请求结束,结果为:",response1) response2 = await other() print("IO 请求结束,结果为:", response2) asyncio.run(func()) print("运行时间:",time.time()-start)
上述的所有代码中都只创建了一个任务,即事件循环列表中只创建了一个任务(async def func
),所以在等待时无法演示切换到其他任务效果。
在程序中需要创建多个任务对象的时候,需要使用Task
对象来实现。
3.2.3 Task 对象
官网解释:
Tasks are used to schedule coroutines concurrently.
When a coroutine is wrapped into a Task with functions like
asyncio.create_task()
the coroutine is automatically scheduled to run soon。
Tasks用于并发调度协程,通过asyncio.create_task(协程对象)
的方式创建Task对象,这样可以让协程加入事件循环中等待被调度执行。除了使用 asyncio.create_task()
函数以外,还可以用低层级的 loop.create_task()
或 ensure_future()
函数。不建议手动实例化 Task 对象。
个人理解:本质上是将协程对象封装成 task 对象,并将协程立即加入事件循环,同时追踪协程的状态。
注意:asyncio.create_task()
函数在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低层级的 asyncio.ensure_future()
函数。
示例1
import asyncio import time start = time.time() async def other(): print("start") await asyncio.sleep(2) print("end") return "啊哈哈哈哈哈" async def main(): print("执行协程函数的内部代码。") # 创建协程,将协程封装到一个Task 对象中,并立即添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态) task1 = asyncio.create_task(other()) task2 = asyncio.create_task(other()) print("执行结束") # 当执行某协程遇到IO操作时,会自动化切换执行其他任务 # 此处的await 是等待相对应的协程全部都执行完毕并获取结果 ret1 = await task1 ret2 = await task2 print(ret1,ret2) asyncio.run(main()) print("运行时间:",time.time()-start)
示例2
import asyncio import time start = time.time() async def other(): print("start") await asyncio.sleep(2) print("end") return "啊哈哈哈哈哈" async def main(): print("main开始") # 创建协程,将协程封装到Task对象中并添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。 task_list = [ asyncio.create_task(other(),name="n1"), asyncio.create_task(other(),name="n2") ] print("main 结束") # 当执行某协程遇到IO操作时,会自动化切换执行其他任务。 # 此处的await是等待所有协程执行完毕,并将所有的返回值保存到done中 # 如果设置了timeout 值,则此处等待的最多秒数,完成的协程返回值写入到done 中,未完成则写到pending中。 done,pending = await asyncio.wait(task_list,timeout=None) # done 的返回值为一个集合,存放着相关的信息 print([i.result() for i in done]) # 使用result()方法获取对应的返回值。 print(done,pending) asyncio.run(main()) print("运行时间:",time.time()-start)
注意:asyncio.wait
源码内部会对列表中的每个协程执行 ensure_future 从而封装为 Task 对象,所以在和wait配合使用时task_list的值为[func(),func()]
也是可以的。
3.2.4 asyncio.Future对象
A
Future
is a special low-level awaitable object that represents an eventual result of an asynchronous operation.
asyncio 中的 Future 对象是一个相对更偏向底层的可对象,通常我们不会直接用到这个对象,而是直接使用 Task 对象来完成任务的并和状态的追踪。( Task 是 Futrue的子类 )
Future 为我们提供了异步编程中的 最终结果 的处理(Task类也具备状态处理的功能)。
示例1:
async def main(): # 获取当前事件循环 loop = asyncio.get_running_loop() # # 创建一个任务(Future对象),这个任务什么都不干。 fut = loop.create_future() # 等待任务最终结果(Future对象),没有结果则会一直等下去。 await fut asyncio.run(main())
示例2:
import asyncio async def set_after(fut): await asyncio.sleep(2) fut.set_result("666") async def main(): # 获取当前事件循环 loop = asyncio.get_running_loop() # 创建一个任务(Future对象),没绑定任何行为,则这个任务永远不知道什么时候结束。 fut = loop.create_future() # 创建一个任务(Task对象),绑定了set_after函数,函数内部在2s之后,会给fut赋值。 # 即手动设置future任务的最终结果,那么fut就可以结束了。 await loop.create_task(set_after(fut)) # 等待 Future对象获取 最终结果,否则一直等下去 data = await fut print(data) asyncio.run(main())
Future对象本身函数进行绑定,所以想要让事件循环获取Future的结果,则需要手动设置。而Task对象继承了Future对象,其实就对Future进行扩展,他可以实现在对应绑定的函数执行完成之后,自动执行set_result
,从而实现自动结束。
虽然,平时使用的是Task对象,但对于结果的处理本质是基于Future对象来实现的。
扩展:支持 await 对象
语 法的对象课成为可等待对象,所以 协程对象
、Task对象
、Future对象
都可以被成为可等待对象。
3.2.5 futures.Future对象
在Python的concurrent.futures
模块中也有一个Future对象,这个对象是基于线程池和进程池实现异步操作时使用的对象。
import time from concurrent.futures import Future from concurrent.futures.thread import ThreadPoolExecutor from concurrent.futures.process import ProcessPoolExecutor def func(value): time.sleep(1) print(value) pool = ThreadPoolExecutor(max_workers=5) # 或 pool = ProcessPoolExecutor(max_workers=5) for i in range(10): fut = pool.submit(func, i) print(fut)
两个Future对象是不同的,他们是为不同的应用场景而设计,例如:concurrent.futures.Future
不支持await语法 等。
官方提示两对象之间不同:
-
unlike asyncio Futures,
concurrent.futures.Future
instances cannot be awaited. -
asyncio.Future.result()
andasyncio.Future.exception()
do not accept the timeout argument. -
asyncio.Future.result()
andasyncio.Future.exception()
raise anInvalidStateError
exception when the Future is not done. -
Callbacks registered with
asyncio.Future.add_done_callback()
are not called immediately. They are scheduled withloop.call_soon()
instead. -
asyncio Future is not compatible with the
concurrent.futures.wait()
andconcurrent.futures.as_completed()
functions.
在Python提供了一个将futures.Future
对象包装成asyncio.Future
对象的函数 asynic.wrap_future
。
接下里你肯定问:为什么python会提供这种功能?
其实,一般在程序开发中我们要么统一使用 asycio 的协程实现异步操作、要么都使用进程池和线程池实现异步操作。但如果 协程的异步
和 进程池/线程池的异步
混搭时,那么就会用到此功能了。
import time import asyncio import concurrent.futures def func1(): # 某个耗时操作 time.sleep(2) return "SB" async def main(): loop = asyncio.get_running_loop() # 1. Run in the default loop's executor ( 默认ThreadPoolExecutor ) # 第一步:内部会先调用 ThreadPoolExecutor 的 submit 方法去线程池中申请一个线程去执行func1函数,并返回一个concurrent.futures.Future对象 # 第二步:调用asyncio.wrap_future将concurrent.futures.Future对象包装为asycio.Future对象。 # 因为concurrent.futures.Future对象不支持await语法,所以需要包装为 asycio.Future对象 才能使用。 fut = loop.run_in_executor(None, func1) result = await fut print('default thread pool', result) # 创建线程池与进程池的示例如下 # 2. Run in a custom thread pool: # with concurrent.futures.ThreadPoolExecutor() as pool: # result = await loop.run_in_executor( # pool, func1) # print('custom thread pool', result) # 3. Run in a custom process pool: # with concurrent.futures.ProcessPoolExecutor() as pool: # result = await loop.run_in_executor( # pool, func1) # print('custom process pool', result) asyncio.run(main())
应用场景:当项目以协程式的异步编程开发时,如果要使用一个第三方模块,而第三方模块不支持协程方式异步编程时,就需要用到这个功能,例如:
import asyncio import requests async def download_image(url): # 发送网络请求,下载图片(遇到网络下载图片的IO请求,自动化切换到其他任务) print("开始下载:", url) loop = asyncio.get_event_loop() # requests模块默认不支持异步操作,所以就使用线程池来配合实现了。 future = loop.run_in_executor(None, requests.get, url) response = await future print('下载完成') # 图片保存到本地文件 file_name = url.rsplit('_')[-1] with open(file_name, mode='wb') as file_object: file_object.write(response.content) if __name__ == '__main__': url_list = [ 'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg', 'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg', 'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg' ] tasks = [download_image(url) for url in url_list] loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.wait(tasks) )
3.2.6 异步迭代器
迭代器的复习:https://www.cnblogs.com/Blogwj123/p/15612256.html
什么是异步迭代器
实现了 __aiter__()
和 __anext__()
方法的对象。__anext__
必须返回一个 awaitable 对象。async for
会处理异步迭代器的 __anext__()
方法所返回的可等待对象,直到其引发一个 StopAsyncIteration
异常。由 PEP 492 引入。
什么是异步可迭代对象?
可在 async for
语句中被使用的对象。必须通过它的 __aiter__()
方法返回一个 asynchronous iterator。由 PEP 492 引入。
import asyncio class Reader(object): """ 自定义异步迭代器(同时也是异步可迭代对象) """ def __init__(self): self.count = 0 async def readline(self): # await asyncio.sleep(1) self.count += 1 if self.count == 100: return None return self.count def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val == None: raise StopAsyncIteration return val async def func(): # 创建异步可迭代对象 async_iter = Reader() # async for 必须要放在async def函数内,否则语法错误。 async for item in async_iter: print(item) asyncio.run(func())
异步迭代器其实没什么太大的作用,只是支持了async for语法而已。
3.2.6 异步上下文管理器
此种对象通过定义 __aenter__()
和 __aexit__()
方法来对 async with
语句中的环境进行控制。由 PEP 492 引入。
import asyncio import pymysql # 定义相关的类 class AsyncContextManager: def __init__(self): self.conn = conn async def do_something(self): # 异步操作数据库 return 666 # 定义__aenter__() async def __aenter__(self): # 异步链接数据库 self.conn = await asyncio.sleep(1) return self # 定义__aexit__() async def __aexit__(self, exc_type, exc, tb): # 异步关闭数据库链接 await asyncio.sleep(1) async def func(): async with AsyncContextManager() as f: result = await f.do_something() print(result) asyncio.run(func())
这个异步的上下文管理器还是比较有用的,平时在开发过程中 打开、处理、关闭 操作时,就可以用这种方式来处理。
3.3 小结
在程序中只要看到async
和await
关键字,其内部就是基于协程实现的异步编程,这种异步编程是通过一个线程在 IO 等待时间去执行其他任务,从而实现并发。
以上就是异步编程的常见操作,内容参考官方文档。
- 中文版:https://docs.python.org/zh-cn/3.8/library/asyncio.html
- 英文本:https://docs.python.org/3.8/library/asyncio.html
4.uvloop
uvloop 是 asyncio 的事件循环的替代方案。事件循环 > 默认 asynico 的事件循环。
使用步骤
# pip 安装 pip3 install uvloop
import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())# 事件循环进行优化 # 编写asyncio的代码,与之前写的代码一致。 # 内部的事件循环自动化会变为uvloop asyncio.run(...)
注意:一个asgi -> uvicorn
内部使用的就是uvloop
5.实战案例
使用协程异步执行相关的操作,一般都具备相关的模块。
5.1 异步操作redis
import asyncio import aioredis async def execute(address, password): print("开始执行", address) # 网络IO操作:创建redis连接 redis = await aioredis.from_url(address,password=password,encoding="utf-8",decode_responses=True) # 网络IO操作:在redis中设置哈希值car,内部在设三个键值对,即: redis = { car:{key1:1,key2:2,key3:3}} # await redis.hmset_dict('car', key1=1, key2=2, key3=3) # 设置相关的值 await redis.set('car','大奔') # 网络IO操作:去redis中获取值 result = await redis.get("car") # result = await redis.hgetall('car', encoding='utf-8')获取哈希值的写法 print(result) # redis.close() # 网络IO操作:关闭redis连接 # await redis.wait_closed() print("结束", address) asyncio.run( execute('redis://127.0.0.1:6379', "password") )
注:由于改依赖库版本的更新,可能某些方法执行出错相关的文档请点击这里参考官网.
5.2 异步操作Mysql
# -*- coding: utf-8 -*- import asyncio import aiomysql async def execute(): # 网络IO操作:连接MySQL conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='111111', db='mysql', ) # 网络IO操作:创建CURSOR cur = await conn.cursor() # 网络IO操作:执行SQL await cur.execute("SELECT Host,User FROM user") # 网络IO操作:获取SQL结果 result = await cur.fetchall() print(result) # 网络IO操作:关闭链接 await cur.close() conn.close() asyncio.run(execute())
5.3 异步爬虫
import aiohttp import asyncio async def fetch(session, url): print("发送请求:", url) async with session.get(url, verify_ssl=False) as response: text = await response.text() print("得到结果:", url, len(text)) return text async def main(): async with aiohttp.ClientSession() as session: url_list = [ 'https://python.org', 'https://www.baidu.com', 'https://www.pythonav.com' ] tasks = [ asyncio.create_task(fetch(session, url)) for url in url_list] done,pending = await asyncio.wait(tasks) if __name__ == '__main__': asyncio.run( main() )
继续努力,终成大器!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器