python runtime_error ai_generated true

RuntimeError: You cannot use async generator in sync context

ID: python/fastapi-async-sync-mixing

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Mixing async and sync code incorrectly in FastAPI dependencies or route handlers, e.g., calling async functions from sync endpoints.

generic

中文

在 FastAPI 依赖或路由处理器中错误地混合异步和同步代码,例如在同步端点中调用异步函数。

Workarounds

  1. 95% success
    Define endpoint as async def if using async functions: @app.get('/')
    async def read_root():
        result = await some_async_function()
  2. 90% success
    Use anyio.to_thread.run_sync for sync functions in async context: from anyio import to_thread
    result = await to_thread.run_sync(sync_function)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    asyncio.run() cannot be called from a running event loop; causes RuntimeError.

  2. 85% fail

    Calling async function returns coroutine object, not result; must be awaited.