fastapi-svelte-template/backend/todo/database/engine.py

28 lines
708 B
Python
Raw Normal View History

"""This module configures and provides the sqlalchemy session factory and base model."""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from todo.config import get_settings
s = get_settings()
# The SQL driver is specified by the DSN-prefix below.
_pg_dsn = f"postgresql+psycopg2://{s.pg_user}:{s.pg_password}@{s.pg_hostname}:{s.pg_port}/{s.pg_dbname}"
engine = create_engine(_pg_dsn, echo=s.debug_mode)
# SQLalchemy session factory
SessionLocal = sessionmaker(engine)
# SQLalchemy base model
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()