异步编程是一种并发编程范式,允许程序在等待 I/O 操作时执行其他任务。Python 通过 asyncio 库和 async/await 语法提供了原生异步支持。

FastAPI 是最受欢迎的现代异步 Web 框架之一,基于 Starlette 构建:
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello')
async def hello():
return {'message': 'Hello, Async World!'}
aiohttp 是异步 HTTP 客户端/服务器框架:
Sanic 是为快速 HTTP 响应设计的异步框架:
Quart 是 Flask 的异步版本:
事件循环是异步编程的核心,负责调度和执行协程:
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('World')
asyncio.run(main())
async def 定义的异步函数class AsyncResource:
async def __aenter__(self):
await self.connect()
return self
async def __aexit__(self, *args):
await self.close()
asyncio.to_thread() 执行同步阻塞操作asyncio.Semaphore 限制同时运行的任务数量asyncio.wait_for() 为协程设置超时try/except 包裹 await 表达式import asyncio
async def fetch_with_timeout(url: str, timeout: float = 10.0):
try:
result = await asyncio.wait_for(fetch_data(url), timeout=timeout)
return result
except asyncio.TimeoutError:
print(f'请求 {url} 超时')
return None
| 场景 | 推荐框架 | 原因 |
|---|---|---|
| REST API | FastAPI | 文档完善、性能好、生态成熟 |
| 微服务 | aiohttp | 灵活、网络层强大 |
| 高性能 API | Sanic | 极致性能优化 |
| Flask 迁移 | Quart | API 兼容、迁移成本低 |
Python 异步编程生态已经非常成熟,选择合适的框架取决于项目需求和团队经验。对于新项目,FastAPI 是当前最推荐的起步选择,兼具性能和开发体验。