Backend Boilerplates python Intermediate

SQLAlchemy Async Session

Async SQLAlchemy engine and session factory wired for FastAPI dependency injection.

python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
import os

engine = create_async_engine(os.environ['DATABASE_URL'], pool_pre_ping=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)

async def get_db():
    async with AsyncSessionLocal() as session:
        yield session

Prerequisites

  • sqlalchemy >= 2.0
  • asyncpg

Pro Tips

  • → Set pool_pre_ping=True to recover from idle drops.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
3 min
Published
Jun 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.