mirror of
https://github.com/cssgunc/compass.git
synced 2025-04-03 19:40:16 -04:00
29 lines
931 B
Python
29 lines
931 B
Python
"""SQLAlchemy DB Engine and Session niceties for FastAPI dependency injection."""
|
|
|
|
import sqlalchemy
|
|
from sqlalchemy.orm import Session
|
|
from .env import getenv
|
|
|
|
|
|
def _engine_str(database: str = getenv("POSTGRES_DATABASE")) -> str:
|
|
"""Helper function for reading settings from environment variables to produce connection string."""
|
|
dialect = "postgresql+psycopg2"
|
|
user = getenv("POSTGRES_USER")
|
|
password = getenv("POSTGRES_PASSWORD")
|
|
host = getenv("POSTGRES_HOST")
|
|
port = getenv("POSTGRES_PORT")
|
|
return f"{dialect}://{user}:{password}@{host}:{port}/{database}"
|
|
|
|
|
|
engine = sqlalchemy.create_engine(_engine_str(), echo=True)
|
|
"""Application-level SQLAlchemy database engine."""
|
|
|
|
|
|
def db_session():
|
|
"""Generator function offering dependency injection of SQLAlchemy Sessions."""
|
|
session = Session(engine)
|
|
try:
|
|
yield session
|
|
finally:
|
|
session.close()
|