tmpl-fastapi/app/sql/db.py
2023-02-20 12:09:43 +04:00

52 lines
1.1 KiB
Python

from typing import AsyncGenerator
from pydantic import BaseSettings
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists
from sqlalchemy_utils import create_database
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)
if not database_exists(db_url):
create_database(db_url)
SessionLocal = sessionmaker(
autoflush=False,
bind=engine,
)
Base = declarative_base()
async def get_db() -> AsyncGenerator[Session, 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()