pythonadvanced

SQLAlchemy Async Session with asyncpg

Use SQLAlchemy 2.0 async sessions with asyncpg for non-blocking database access in async pipelines.

python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from sqlalchemy import Column, Integer, String, select
import asyncio

engine = create_async_engine('postgresql+asyncpg://user:pass@localhost/db', echo=False)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

class Base(DeclarativeBase): pass

class User(Base):
    __tablename__ = 'users'
    id   = Column(Integer, primary_key=True)
    name = Column(String)

async def get_users():
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(User).limit(10))
        return result.scalars().all()

asyncio.run(get_users())

Use Cases

  • async web services
  • non-blocking DB access
  • FastAPI backends

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.