from typing import Generator from pydantic import BaseSettings from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker from sqlalchemy.ext.declarative import declarative_base class SqlSettings(BaseSettings): db_host: str = '${REPO_NAME_SNAKE}_db' db_port: int = 3306 db_user: str = '${REPO_NAME_SNAKE}' db_password: str = '' db_database: str = '${REPO_NAME_SNAKE}' sql_settings = SqlSettings() db_url = ( 'mysql://{db_user}:{db_password}@' '{db_host}:{db_port}/${db_database}' ).format(**sql_settings.dict()) engine = create_engine(db_url) SessionLocal = sessionmaker( autocommit=False, autoflush=False, bind=engine, ) Base = declarative_base() def get_db() -> Generator[Session, None, None]: """FastAPI dependency returning database Session object. Code is copied from the official docs Yields: SQLAlchemy Session object """ db = SessionLocal() try: yield db finally: db.close()