Files
iptv-manager-service/app/utils/database.py
Stefano cebbb9c1a8
All checks were successful
AWS Deploy on Push / build (push) Successful in 1m4s
Added pytest configuration and first 4 unit tests
2025-05-27 17:37:05 -05:00

42 lines
1.6 KiB
Python

import os
import boto3
from app.models import Base
from .constants import AWS_REGION
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from functools import lru_cache
def get_db_credentials():
"""Fetch and cache DB credentials from environment or SSM Parameter Store"""
if os.getenv("MOCK_AUTH", "").lower() == "true":
return (
f"postgresql://{os.getenv('DB_USER')}:{os.getenv('DB_PASSWORD')}"
f"@{os.getenv('DB_HOST')}/{os.getenv('DB_NAME')}"
)
ssm = boto3.client('ssm', region_name=AWS_REGION)
try:
host = ssm.get_parameter(Name='/iptv-updater/DB_HOST', WithDecryption=True)['Parameter']['Value']
user = ssm.get_parameter(Name='/iptv-updater/DB_USER', WithDecryption=True)['Parameter']['Value']
password = ssm.get_parameter(Name='/iptv-updater/DB_PASSWORD', WithDecryption=True)['Parameter']['Value']
dbname = ssm.get_parameter(Name='/iptv-updater/DB_NAME', WithDecryption=True)['Parameter']['Value']
return f"postgresql://{user}:{password}@{host}/{dbname}"
except Exception as e:
raise RuntimeError(f"Failed to fetch DB credentials from SSM: {str(e)}")
# Initialize engine and session maker
engine = create_engine(get_db_credentials())
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def init_db():
"""Initialize database by creating all tables"""
Base.metadata.create_all(bind=engine)
def get_db():
"""Dependency for getting database session"""
db = SessionLocal()
try:
yield db
finally:
db.close()