python runtime_error ai_generated true

运行时错误:不能在同步上下文中使用异步生成器

RuntimeError: You cannot use async generator in sync context

ID: python/fastapi-async-sync-mixing-error

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

版本兼容性

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

根因分析

错误地混合异步和同步代码,例如在同步路由中使用异步生成器。

English

Mixing async and sync code incorrectly, such as using an async generator in a synchronous route or vice versa.

generic

解决方案

  1. 95% 成功率
    Define the route as async if you need to use async generators: @app.get('/')\nasync def read_root():\n    async for item in async_gen():\n        yield item
  2. 80% 成功率
    For sync routes, use a sync generator or collect items with asyncio.run() in a separate function.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Adding asyncio.run() inside a sync route can cause event loop conflicts.

  2. 70% 失败

    Converting an async generator to a list with list() works only in async context, not sync.