python-async-concurrency

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Async & Concurrency

Python异步与并发

When to use this skill

何时使用该技能

  • Writing high-concurrency I/O bound applications (FastAPI, bots, scrapers).
  • Using
    asyncio
    ,
    aiohttp
    , or
    httpx
    .
  • Managing background tasks or task queues.
  • 编写高并发I/O密集型应用(FastAPI、机器人、爬虫)。
  • 使用
    asyncio
    aiohttp
    httpx
  • 管理后台任务或任务队列。

1. Asyncio Basics

1. Asyncio基础

  • Entry Point: Use
    asyncio.run(main())
    for the entry point.
  • TaskGroups: Use
    async with asyncio.TaskGroup() as tg
    (Python 3.11+) instead of
    gather()
    for better error handling/cancellation.
  • Blocking Code: Run blocking (CPU-bound) code in
    await asyncio.to_thread(...)
    .
  • 入口点:使用
    asyncio.run(main())
    作为入口。
  • TaskGroups:使用
    async with asyncio.TaskGroup() as tg
    (Python 3.11+)替代
    gather()
    ,以获得更好的错误处理/取消机制。
  • 阻塞代码:在
    await asyncio.to_thread(...)
    中运行阻塞(CPU密集型)代码。

2. HTTP Clients

2. HTTP客户端

  • HTPX/AIOHTTP: Use
    httpx.AsyncClient
    or
    aiohttp.ClientSession
    as a context manager.
  • 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
    )。