sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called
can't call await_only() here. Was IO attempted in an unexpected place?
Not confirmed yet · posted Nov 5
Cause
a plain attribute access (lazy-loaded relationship, or a column expired by commit) tried to emit SQL; under asyncio IO only runs inside an awaited call.
Fix
risk: low
+from sqlalchemy.orm import selectinload-users = (await session.scalars(select(User))).all()+users = (await session.scalars(select(User).options(selectinload(User.posts)))).all()-SessionLocal = async_sessionmaker(engine)+SessionLocal = async_sessionmaker(engine, expire_on_commit=False) # commit no longer expires loaded attrs# one object: await session.refresh(user, ["posts"]), or Base(AsyncAttrs, DeclarativeBase) + await user.awaitable_attrs.postsDon’t try
keep the AsyncSession open longer and touch the relationship inside the async with block — that fixes DetachedInstanceError in sync code, not this: any implicit lazy load fails under asyncio even while the AsyncSession is open.
pip install greenlet because the error says MissingGreenlet — greenlet is already installed (2.0 without it raises ValueError: the greenlet library is required...); the name means the IO ran outside SQLAlchemy's greenlet context.
Related
- sqlalchemy.exc.ArgumentError: Mapped class aliased(<Base>) referenced in option <option>(aliased(<Base>).<attr>) does not apply to any of the root entities in this query, e.g. <Subclass>. Please specify the full path from one of the root entities to the target attribute.
- SAWarning: Did not recognize type 'tsquery' of column '<col>'
- sqlalchemy.exc.TimeoutError: QueuePool limit of size <n> overflow <n> reached, connection timed out, timeout <n>