python runtime_error ai_generated true

RuntimeWarning: 协程 'sleep' 从未被等待 / requests.exceptions.ConnectionError: ('连接中止。', RemoteDisconnected('远程端关闭连接而未响应'))

RuntimeWarning: coroutine 'sleep' was never awaited / requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

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

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

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

在 async def 端点内进行阻塞式同步调用(requests、time.sleep、重 IO)会阻塞事件循环,导致超时和连接中断。

English

Blocking synchronous calls (requests, time.sleep, heavy IO) inside an async def endpoint block the event loop, causing timeouts and dropped connections.

generic

解决方案

  1. 95% 成功率
    import httpx
    async with httpx.AsyncClient() as client:
        r = await client.get(url)
  2. 90% 成功率
    from starlette.concurrency import run_in_threadpool
    result = await run_in_threadpool(blocking_fn, arg)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Does not unblock the event loop; requests still queue.

  2. 70% 失败

    Each worker still has one blocked loop; capacity is limited.