Problems with Asynchronous Request Handling in FastAPI and SQLAlchemy Transactions
I'm working with an scenario with handling asynchronous requests in a FastAPI application that's using SQLAlchemy for database transactions. When I make an async call to my endpoint that involves a database transaction, I'm getting the following behavior: `sqlalchemy.exc.InvalidRequestError: This session is in 'expired' state`. This typically happens when the connection to the database is lost or the session gets closed unexpectedly. Hereβs a simplified version of the code Iβm using: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname" engine = create_async_engine(DATABASE_URL, echo=True) Base = declarative_base() async_session = async_sessionmaker(bind=engine, expire_on_commit=False) app = FastAPI() class Item(Base): __tablename__ = 'items' id = Column(Integer, primary_key=True) name = Column(String) @app.post('/items/') async def create_item(item: Item, session: AsyncSession = Depends(async_session)): session.add(item) await session.commit() return item ``` I've already tried ensuring that my database connection is stable and that I'm not closing the session prematurely. I've also checked that the session is properly passed and scoped to each request. Interestingly, if I change the endpoint to handle requests synchronously (using a standard function instead of async), it works fine without throwing any errors. Could this be an scenario with how FastAPI handles async requests, or is it possible that I'm not managing my SQLAlchemy session lifecycle correctly? Any insights would be appreciated!