mirror of
https://gitverse.ru/kpa39l/md2vk.git
synced 2026-09-29 18:05:04 +00:00
37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
"""База данных: async engine, сессии, инициализация."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
from app.config import settings
|
|
|
|
# Создаём каталог для БД, если SQLite
|
|
_db_path = settings.database_url.replace("sqlite+aiosqlite:///", "")
|
|
if _db_path != settings.database_url:
|
|
Path(_db_path).parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
engine = create_async_engine(settings.database_url, echo=False)
|
|
async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
|
|
|
|
async def get_db() -> AsyncSession:
|
|
"""FastAPI-зависимость: сессия БД."""
|
|
async with async_session_factory() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def init_db():
|
|
"""Создаёт таблицы при старте."""
|
|
from app.models import Base # noqa: F401 — импорт моделей для регистрации
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all) |