from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from pydantic_settings import BaseSettings from typing import AsyncGenerator import os class Settings(BaseSettings): DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql+asyncpg://app_user:secure_password_123@postgres:5432/messenger_db") REDIS_URL: str = os.getenv("REDIS_URL", "redis://redis:6379/0") SECRET_SESSION_KEY: str = os.getenv("SECRET_SESSION_KEY", "super_secret_random_string_change_in_production_12345") SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600")) class Config: env_file = ".env" settings = Settings() engine = create_async_engine( settings.DATABASE_URL, echo=False, pool_size=10, max_overflow=20, pool_timeout=30, pool_recycle=1800 ) async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_db() -> AsyncGenerator[AsyncSession, None]: async with async_session_maker() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close()