← ClaudeAtlas

py-async-patternslisted

Async/await patterns for FastAPI and SQLAlchemy. Use when working with async code, database sessions, concurrent operations, or debugging async issues in Python.
aiskillstore/marketplace · ★ 329 · API & Backend · score 79
Install: claude install-skill aiskillstore/marketplace
# Python Async Patterns ## Problem Statement Async Python is powerful but error-prone. Race conditions, session leaks, and connection pool issues are common pitfalls in async codebases. --- ## Pattern: AsyncSession Lifecycle **Problem:** Session must be scoped to request. Leaking sessions causes stale data and connection exhaustion. ```python # ✅ CORRECT: Session scoped to request via dependency async def get_session() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: yield session # Session automatically closed after request # Usage in endpoint @router.get("/users/{user_id}") async def get_user( user_id: UUID, session: AsyncSession = Depends(get_session), ) -> UserRead: result = await session.execute(select(User).where(User.id == user_id)) return result.scalar_one() # ❌ WRONG: Global session (stale data, connection leaks) _global_session = None # NEVER do this async def get_user(user_id: UUID): result = await _global_session.execute(...) # Stale, shared state ``` **Why it matters:** Each request needs isolated database state. Shared sessions see stale data and can't be safely committed. --- ## Pattern: Concurrent vs Sequential Queries **Problem:** Running independent queries sequentially wastes time. But dependent queries must be sequential. ```python # ✅ CORRECT: Concurrent independent queries async def get_dashboard_data(user_id: UUID, session: AsyncSession): # These don't depend on eac