python runtime_error ai_generated true

sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here.

ID: python/fastapi-sqlalchemy-async-session-not-bound

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Lazy-loading a relationship on an AsyncSession outside an awaited greenlet context, e.g. in template rendering or sync code.

generic

中文

在异步会话之外的 greenlet 上下文中对 AsyncSession 的关系进行延迟加载,例如在模板渲染或同步代码中。

Workarounds

  1. 94% success
    from sqlalchemy.orm import selectinload
    result = await session.execute(select(User).options(selectinload(User.posts)))
  2. 88% success
    await session.refresh(user, ['posts'])

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Dynamic still requires I/O; the greenlet error persists.

  2. 85% fail

    Blocks the event loop and breaks FastAPI async handling.