asyncio
是 Python 中用于编写异步代码的库,适用于 I/O 密集型任务(如网络请求、文件读写、数据库操作等)。它通过事件循环、协程和 await
关键字实现异步编程。
主要用法
- 事件循环:管理异步任务的执行。
- 协程:使用
async def
定义的函数,通过await
暂停执行,等待异步操作完成。 - 任务:通过
asyncio.create_task()
创建的协程对象,用于并发执行。 - Future:表示异步操作的最终结果。
- 异步上下文管理器:使用
async with
管理异步资源。 - 异步迭代器:使用
async for
遍历异步生成的数据。
应用场景
- 网络请求:并发处理多个 HTTP 请求。
- 文件 I/O:异步读写文件。
- 数据库操作:异步执行数据库查询。
- Web 服务器:处理大量并发请求。
- 实时数据处理:如聊天服务器、实时数据流处理。
实例
1. 并发网络请求
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'https://example.com',
'https://example.org',
'https://example.net',
]
tasks = [fetch(url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result[:100]) # 打印每个响应的前100个字符
asyncio.run(main())
2. 异步文件读写
import asyncio
async def read_file(filename):
with open(filename, 'r') as f:
return f.read()
async def write_file(filename, content):
with open(filename, 'w') as f:
f.write(content)
async def main():
content = await read_file('input.txt')
await write_file('output.txt', content.upper())
asyncio.run(main())
3. 异步数据库操作
import asyncio
import asyncpg
async def fetch_data():
conn = await asyncpg.connect(user='user', password='password', database='db', host='127.0.0.1')
result = await conn.fetch('SELECT * FROM my_table')
await conn.close()
return result
async def main():
data = await fetch_data()
for record in data:
print(record)
asyncio.run(main())
测试数据
1. 网络请求测试数据
https://example.com
https://example.org
https://example.net
2. 文件读写测试数据
input.txt
文件内容:
Hello, World!
This is a test file.
output.txt
文件内容(运行后):
HELLO, WORLD!
THIS IS A TEST FILE.
3. 数据库操作测试数据
- 表
my_table
结构:
CREATE TABLE my_table (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
- 插入测试数据:
INSERT INTO my_table (name) VALUES ('Alice'), ('Bob'), ('Charlie');
总结
asyncio
适用于 I/O 密集型任务,能显著提升并发性能。通过事件循环和协程,开发者可以编写高效的异步代码。