SRE & AI 实践录

Python 异步编程模式:从协程到事件循环深度剖析

· 更新于 2026-07-26 ⏱️ 阅读约 2 分钟 (620 字) Python 异步 API

深入解析 Python asyncio 库的核心机制,从协程定义、事件循环调度到异步上下文管理,帮助开发者编写高性能并发代码。

一、异步编程基础

Python 的 asyncio 库提供了基于事件循环的协程并发模型,适用于 I/O 密集型和高并发的应用场景。理解协程、事件循环和任务调度是掌握异步编程的关键。

二、核心示例

以下示例展示了如何使用 async/await 编写并发 API 请求,以及使用 asyncio.gather 并行执行多个协程。

Python 异步示例

python
import asyncio
import aiohttp
from typing import List

async def fetch_url(session: aiohttp.ClientSession, url: str) -> dict:
    """异步获取 URL 内容"""
    async with session.get(url) as response:
        return await response.json()

async def fetch_all(urls: List[str]) -> List[dict]:
    """并发获取所有 URL"""
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        return await asyncio.gather(*tasks, return_exceptions=True)

async def main():
    urls = [
        "https://api.example.com/users",
        "https://api.example.com/posts",
        "https://api.example.com/comments",
    ]
    results = await fetch_all(urls)
    for i, result in enumerate(results):
        print(f"请求 {i}: {'成功' if not isinstance(result, Exception) else '失败'}")

if __name__ == "__main__":
    asyncio.run(main())

运行脚本

bash
#!/bin/bash
# 异步程序运行脚本
python3 -m pip install aiohttp  # 安装依赖
python3 async_fetch.py          # 运行异步程序

三、最佳实践

使用 asyncio.create_task 创建后台任务,使用 asyncio.Semaphore 控制并发量,使用 asyncio.timeout 管理超时。避免在协程中执行 CPU 密集型操作,如需并行计算应使用 concurrent.futures

本文作者:技术领航员 | 许可协议:CC BY-NC-SA 4.0

本文链接:https://sre-ai-blog.pages.dev/zh/posts/python-async-patterns/(转载请注明出处)