website-practice/backend/app/database.py

41 lines
1.1 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 sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from .config import config
from .models import Base
engine = create_async_engine(
url=config.postgres_url,
echo=config.postgres_engine_echo,
)
session_maker = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
async def get_session():
async with session_maker() as session: # pyrefly: ignore
return session
async def create_db(engine: AsyncEngine) -> None:
"""Create the entire database from the base model."""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def drop_db(engine: AsyncEngine) -> None:
"""Drop the entire database from the base model."""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)