invix_test_task/api/app/db.py

31 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
engine = create_async_engine(settings.database_url, pool_pre_ping=True)
SessionFactory = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncIterator[AsyncSession]:
"""Одна сессия на запрос. Коммит только если эндпоинт не бросил исключение.
scope=function у Depends закрывает сессию до отправки ответа, поэтому
клиент не получает успех раньше фиксации транзакции.
"""
async with SessionFactory() as session:
try:
yield session
except Exception:
await session.rollback()
raise
else:
await session.commit()