python-async-concurrency
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Async & Concurrency
Python异步与并发
When to use this skill
何时使用该技能
- Writing high-concurrency I/O bound applications (FastAPI, bots, scrapers).
- Using ,
asyncio, oraiohttp.httpx - Managing background tasks or task queues.
- 编写高并发I/O密集型应用(FastAPI、机器人、爬虫)。
- 使用、
asyncio或aiohttp。httpx - 管理后台任务或任务队列。
1. Asyncio Basics
1. Asyncio基础
- Entry Point: Use for the entry point.
asyncio.run(main()) - TaskGroups: Use (Python 3.11+) instead of
async with asyncio.TaskGroup() as tgfor better error handling/cancellation.gather() - Blocking Code: Run blocking (CPU-bound) code in .
await asyncio.to_thread(...)
- 入口点:使用作为入口。
asyncio.run(main()) - TaskGroups:使用(Python 3.11+)替代
async with asyncio.TaskGroup() as tg,以获得更好的错误处理/取消机制。gather() - 阻塞代码:在中运行阻塞(CPU密集型)代码。
await asyncio.to_thread(...)
2. HTTP Clients
2. HTTP客户端
- HTPX/AIOHTTP: Use or
httpx.AsyncClientas a context manager.aiohttp.ClientSession - Singleton: Reuse the client session across requests; do not create a new one per request.
- HTPX/AIOHTTP:将或
httpx.AsyncClient作为上下文管理器使用。aiohttp.ClientSession - 单例模式:在多个请求间复用客户端会话;不要为每个请求创建新的会话。
3. Pitfalls
3. 常见陷阱
- Sync in Async: Never call blocking sync functions (requests, time.sleep) inside async functions.
- Fire and Forget: Avoid unreferenced background tasks; keep a reference to prevent garbage collection (or use ).
TaskGroup
- 异步中调用同步:切勿在异步函数内调用阻塞式同步函数(如requests、time.sleep)。
- “即发即弃”任务:避免无引用的后台任务;保留引用以防止被垃圾回收(或使用)。
TaskGroup