python runtime_error ai_generated true

RuntimeError: You cannot use async generator in sync context

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success
    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% success
    For sync routes, use a sync generator or collect items with asyncio.run() in a separate function.

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 70% fail

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