Python教程——20.协程 - 2 python2.7 协程
wptr33 2024-12-25 16:03 15 浏览
异步编程
asyncio.Future 对象
Task 继承 Future, Task对象内部中的await结果的处理基于Future对象来的
在Future对象中会保存当前执行的这个协程任务的状态,如果当前任务状态为finished, 则await不再等待。
示例1:
import asyncio
async def main():
# 获取当前事件循环
loop = asyncio.get_running_loop()
# 创建一个任务[Future对象] 当前没有任何任务
fut = loop.create_future()
# 等待任务的最终结果,没有结果则一直等待
await fut
asyncio.run(main())
示例2:
import asyncio
async def set_after(fut):
await asyncio.sleep(2)
fut.set_result('这是一个测试结果')
async def main():
# 获取事件循环
loop = asyncio.get_running_loop()
# 创建一个任务, 并且当前任务没有绑定任何行为, 则这个任务永远不知道什么时候结束
fut = loop.create_future()
# 手动设置future任务的最终结果
await loop.create_task(set_after(fut))
# 等待Future对象获取最终的结果, 否则就一直等
data = await fut
print(data)
asyncio.run(main())
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)
一般情况下,代码编写需要统一编程风格,简而言之,就是如果使用的是线程/进程,则整个程序都统一使用线程/进程。
只有一种情况可能会进行交叉编程。一个项目中的所有IO请求为协程异步请求,假设MySQL数据库版本过低导致无法使用协程进行并发存储,这种情况会使用线程/进程完成并发存储任务。
import time
import asyncio
import concurrent.futures
def func_1():
time.sleep(2)
return '测试'
async def main():
loop = asyncio.get_running_loop()
# 在协程函数中运行普通函数 在执行函数时,协程内部会自动创建一个线程池来运行任务
# run_in_executor()方法第一个参数为None时则默认创建一个线程池
fut = loop.run_in_executor(None, func_1)
result = await fut
print('当前方式会自动创建一个线程池去执行普通函数: ', result)
# 在协程函数中运行基于线程池的任务, 效果与以上代码一致
with concurrent.futures.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, func_1)
print('在线程池中得到的执行结果: ', result)
# 在协程函数中运行基于进程池的任务
with concurrent.futures.ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, func_1)
print('在进程池中得到的执行结果: ', result)
if __name__ == "__main__":
asyncio.run(main())
案例:asyncio + 不支持异步的模块(requests)
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 f:
f.write(response.content)
if __name__ == '__main__':
url_list = [
'http://pic.bizhi360.com/bbpic/98/10798.jpg',
'http://pic.bizhi360.com/bbpic/92/10792.jpg',
'http://pic.bizhi360.com/bbpic/86/10386.jpg'
]
tasks = [download_image(url) for url in url_list]
# loop = asyncio.get_event_loop()
# loop.run_until_complete(asyncio.wait(tasks))
asyncio.run(asyncio.wait(tasks))
异步迭代器
什么是异步迭代器?
实现了__aiter__() 和 __anext__() 方法的对象。__aiter__() 必须返回一个awaitable对象。async for会处理异步迭代器的 __anext__()方法所返回的可等待对象,直到引发一个StopAsyncIteration异常。
什么是异步可迭代对象?
可在async for语句中被使用的对象。必须通过它的__aiter__()方法返回一个asynchronous iterator。
import asyncio
# 自定义异步迭代器
class Reader:
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 is None:
raise StopAsyncIteration
return val
async def func():
obj = Reader()
# 异步for循环必须在协程函数内执行,协程函数名称随意取名
async for item in obj:
print(item)
asyncio.run(func())
异步上下文管理器
此种现象通过定义__aenter__()和__axeit__()方法来对async with语句中的环境进行控制。
import asyncio
class AsyncContextManager:
def __init__(self, conn=None):
self.conn = conn
async def do_something(self):
# 异步操作数据库
return 'crud'
async def __aenter__(self):
# 异步连接数据库
self.conn = await asyncio.sleep(1)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
# 异步关闭数据库连接
await asyncio.sleep(1)
async def func():
# 上下文管理器处理也需要在协程函数中运行
async with AsyncContextManager() as f:
result = await f.do_something()
print(result)
asyncio.run(func())
uvloop
是asyncio的事件循环的替代方案。
uvloop事件循环的执行效率比asyncio默认的事件循环的效率高。
# pip install uvloop
import asyncio
import uvloop
# 设置事件循环为uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# 编写的asyncio代码与之前一致
# 内部事件循环会自动切到uvloop
asyncio.run(...)
实战案例
异步操作 Redis
在使用python代码操作redis时,像连接、读取/写入、断开都是IO操作。
pip install aioredis==1.3.1
案例1:
import asyncio
import aioredis
async def execute(address):
print('开始执行: ', address)
# 网络IO 创建redis连接
redis = await aioredis.create_redis(address)
# 网络IO 在redis中设置哈希值
await redis.hmset_dict('car', key1=1, key2=2, key3=3)
# 网络IO 获取redis中的值
result = await redis.hgetall('car', encoding='utf-8')
print(result)
redis.close()
# 网络IO 关闭redis连接
await redis.wait_closed()
print('结束...')
asyncio.run(execute('redis://127.0.0.1:6379/0'))
案例2:
import asyncio
import aioredis
async def execute(address, password):
print('开始执行: ', address)
# 网络IO 创建redis连接
redis = await aioredis.create_redis_pool(address, password=password)
# 网络IO 在redis中设置哈希值
await redis.hmset_dict('car', key1=1, key2=2, key3=3)
# 网络IO 获取redis中的值
result = await redis.hgetall('car', encoding='utf-8')
print(result)
redis.close()
# 网络IO 关闭redis连接
await redis.wait_closed()
print('结束...')
task_list = [
execute('redis://localhost:6379/0', None),
execute('redis://localhost:6379/1', None)
]
asyncio.run(asyncio.wait(task_list))
异步 MySQL
pip install aiomysql
案例1:
import asyncio
import aiomysql
async def execute():
# 网络IO操作 连接mysql
conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='mysql')
# 网络IO操作 创建游标
cursor = await conn.cursor()
# 网络IO操作 执行sql
await cursor.execute('select host,user from user')
# 网络IO操作 获取sql结果
result = await cursor.fetchall()
print(result)
# 网络IO操作
await cursor.close()
conn.close()
asyncio.run(execute())
案例2:
import asyncio
import aiomysql
async def execute(host, password):
print('开始连接:', host)
# 网络IO操作 连接mysql
conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='mysql')
# 网络IO操作 创建游标
cursor = await conn.cursor()
# 网络IO操作 执行sql
await cursor.execute('select host,user from user')
# 网络IO操作 获取sql结果
result = await cursor.fetchall()
print(result)
# 网络IO操作
await cursor.close()
conn.close()
print('结束:', host)
task_list = [
execute('localhost', 'root'),
execute('localhost', 'root')
]
asyncio.run(asyncio.wait(task_list))
FastAPI框架
pip install uvicorn
pip install fastapi
示例:
import uvicorn
import asyncio
import aioredis
from fastapi import FastAPI
app = FastAPI()
# 创建redis连接池
REDIS_POOL = aioredis.ConnectionsPool('redis://localhost:6379', password=None, minsize=1, maxsize=10)
@app.get('/')
def index():
# 普通视图函数
return {'message': 'hello world'}
@app.get('/red')
async def red():
# 异步视图
print('请求来了...')
await asyncio.sleep(3)
# 获取连接池中的一个链接
conn = await REDIS_POOL.acquire()
redis = aioredis.Redis(conn)
# 设置值
await redis.hmset_dict('car_fastApi', key1=1, key2=2, key3=3)
# 读取值
result = await redis.hgetall('car_fastApi', encoding='utf-8')
print(result)
# 将单个连接归还给连接池
REDIS_POOL.release(conn)
return result
if __name__ == '__main__':
# fastapi_test为当前这个脚本文件的名称
uvicorn.run("fastapi_test:app", host='127.0.0.1', port=5000, log_level='info')
爬虫
import asyncio
import aiohttp
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))
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
'https://python.org',
'https://www.baidu.com',
]
tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
await asyncio.wait(tasks)
if __name__ == '__main__':
asyncio.run(main())
相关推荐
- Linux高性能服务器设计
-
C10K和C10M计算机领域的很多技术都是需求推动的,上世纪90年代,由于互联网的飞速发展,网络服务器无法支撑快速增长的用户规模。1999年,DanKegel提出了著名的C10问题:一台服务器上同时...
- 独立游戏开发者常犯的十大错误
-
...
- 学C了一头雾水该咋办?
-
学C了一头雾水该怎么办?最简单的方法就是你再学一遍呗。俗话说熟能生巧,铁杵也能磨成针。但是一味的为学而学,这个好像没什么卵用。为什么学了还是一头雾水,重点就在这,找出为什么会这个样子?1、概念理解不深...
- C++基础语法梳理:inline 内联函数!虚函数可以是内联函数吗?
-
上节我们分析了C++基础语法的const,static以及this指针,那么这节内容我们来看一下inline内联函数吧!inline内联函数...
- C语言实战小游戏:井字棋(三子棋)大战!文内含有源码
-
井字棋是黑白棋的一种。井字棋是一种民间传统游戏,又叫九宫棋、圈圈叉叉、一条龙、三子旗等。将正方形对角线连起来,相对两边依次摆上三个双方棋子,只要将自己的三个棋子走成一条线,对方就算输了。但是,有很多时...
- C++语言到底是不是C语言的超集之一
-
C与C++两个关系亲密的编程语言,它们本质上是两中语言,只是C++语言设计时要求尽可能的兼容C语言特性,因此C语言中99%以上的功能都可以使用C++完成。本文探讨那些存在于C语言中的特性,但是在C++...
- 在C++中,如何避免出现Bug?
-
C++中的主要问题之一是存在大量行为未定义或对程序员来说意外的构造。我们在使用静态分析器检查各种项目时经常会遇到这些问题。但正如我们所知,最佳做法是在编译阶段尽早检测错误。让我们来看看现代C++中的一...
- ESL-通过事件控制FreeSWITCH
-
通过事件提供的最底层控制机制,允许我们有效地利用工具箱,适时选择使用其中的单个工具。FreeSWITCH是一个核心交换与混合矩阵,它周围有几十个模块提供各种功能特性。我们完全控制了所有的即时信息,这些...
- 物理老师教你学C++语言(中篇)
-
一、条件语句与实验判断...
- C语言入门指南
-
当然!以下是关于C语言入门编程的基础介绍和入门建议,希望能帮你顺利起步:C语言入门指南...
- C++选择结构,让程序自动进行决策
-
什么是选择结构?正常的程序都是从上至下顺序执行,这就是顺序结构...
- C++特性使用建议
-
1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...
- C++程序员学习Zig指南(中篇)
-
1.复合数据类型结构体与方法的对比C++类:...
- 研一自学C++啃得动吗?
-
研一自学C++啃得动吗?在开始前我有一些资料,是我根据网友给的问题精心整理了一份「C++的资料从专业入门到高级教程」,点个关注在评论区回复“888”之后私信回复“888”,全部无偿共享给大家!!!个人...
- C++关键字介绍
-
下表列出了C++中的常用关键字,这些关键字不能作为变量名或其他标识符名称。1、autoC++11的auto用于表示变量的自动类型推断。即在声明变量的时候,根据变量初始值的类型自动为此变量选择匹配的...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mysql max (33)
- vba instr (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)