Performance: SQLAlchemy setup with FastAPI
MEDIUM IMPACT
This affects the server response time and database query efficiency, impacting how fast the API can send data to the user.
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker engine = create_async_engine('sqlite+aiosqlite:///./test.db') AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_db(): async with AsyncSessionLocal() as session: yield session
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine('sqlite:///./test.db') SessionLocal = sessionmaker(bind=engine) def get_db(): db = SessionLocal() try: yield db finally: db.close()
| Pattern | DB Connection Type | Event Loop Blocking | Response Latency | Verdict |
|---|---|---|---|---|
| Synchronous SQLAlchemy session | Sync | Blocks event loop | Higher latency under load | [X] Bad |
| Async SQLAlchemy session with async driver | Async | Non-blocking | Lower latency, better throughput | [OK] Good |