python runtime_error ai_generated true

RuntimeWarning: 协程 'get_db' 从未被 await

RuntimeWarning: coroutine 'get_db' was never awaited

ID: python/fastapi-depends-async-generator-not-closed

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

版本兼容性

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

根因分析

异步依赖(async def 或异步生成器)被当作普通函数使用,或漏写 Depends 导致返回未 await 的协程。

English

An async dependency (async def or async generator) is used as a plain function, or Depends is missing so the coroutine is returned unawaited.

generic

解决方案

  1. 93% 成功率
    Declare the dependency with Depends:
    def route(db=Depends(get_db)): ...
  2. 88% 成功率
    Use an async generator dependency that yields and cleans up in finally.

无效尝试

常见但无效的做法:

  1. 60% 失败

    Blocks the event loop and may break async DB drivers.

  2. 80% 失败

    Returns a coroutine/generator you then misuse; resources leak.