Files
iptv-manager-service/app/utils/database.py
Stefano 5767124031
All checks were successful
AWS Deploy on Push / build (push) Successful in 2m41s
Fixed database credential retrieval
2025-05-21 15:05:12 -05:00

35 lines
1.3 KiB
Python

import os
import boto3
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from functools import lru_cache
@lru_cache(maxsize=1)
def get_db_credentials():
"""Fetch and cache DB credentials from SSM Parameter Store"""
ssm = boto3.client('ssm')
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)}")
engine = create_engine(get_db_credentials())
# Create all tables
from app.models import Base
Base.metadata.create_all(bind=engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
"""Dependency for getting database session"""
db = SessionLocal()
try:
yield db
finally:
db.close()