tmpl-fastapi/app/sql/db.py

53 lines
1.1 KiB
Python
Raw Normal View History

2023-02-20 11:09:43 +03:00
from typing import AsyncGenerator
2023-02-19 16:49:44 +03:00
from pydantic import BaseSettings
from sqlalchemy import create_engine
2023-02-20 11:09:43 +03:00
from sqlalchemy_utils import database_exists
from sqlalchemy_utils import create_database
2023-02-19 16:49:44 +03:00
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}@'
2023-02-20 11:09:43 +03:00
'{db_host}:{db_port}/{db_database}'
2023-02-19 16:49:44 +03:00
).format(**sql_settings.dict())
2023-02-20 11:09:43 +03:00
2023-02-19 16:49:44 +03:00
engine = create_engine(db_url)
2023-02-20 11:09:43 +03:00
if not database_exists(db_url):
create_database(db_url)
2023-02-19 16:49:44 +03:00
SessionLocal = sessionmaker(
autoflush=False,
bind=engine,
)
2023-02-20 11:09:43 +03:00
2023-02-19 16:49:44 +03:00
Base = declarative_base()
2023-02-20 11:09:43 +03:00
async def get_db() -> AsyncGenerator[Session, None]:
2023-02-19 16:49:44 +03:00
"""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()