python runtime_error ai_generated true

WARNING: 在异步端点中检测到阻塞调用: time.sleep(5)

WARNING: Blocking call detected in async endpoint: time.sleep(5)

ID: python/fastapi-event-loop-blocking-call

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-06-30首次发现

版本兼容性

版本状态引入弃用备注
3.9+ active
3.10+ active
3.11+ active
3.12+ active

根因分析

在 async def 端点中直接调用了同步阻塞函数(time.sleep、requests、CPU 密集型工作),冻结了事件循环。

English

A synchronous blocking function (time.sleep, requests, CPU-bound work) was called directly inside an async def endpoint, freezing the event loop.

generic

解决方案

  1. 95% 成功率
    from fastapi.concurrency import run_in_threadpool
    
    @app.get('/x')
    async def x():
        result = await run_in_threadpool(blocking_fn, arg)
  2. 93% 成功率
    async with httpx.AsyncClient() as client:
        r = await client.get(url)

无效尝试

常见但无效的做法:

  1. 75% 失败

    Each worker still blocks its own loop; throughput does not improve for a single request.

  2. 80% 失败

    Yielding once does not prevent the subsequent block from stalling the loop.