Refactor application configuration; implement dynamic database URI setup based on environment variables for improved flexibility and maintainability

This commit is contained in:
Yaro Kasear 2025-06-20 13:48:03 -05:00
parent 86a4e4d22f
commit e67ae63eb8
10 changed files with 88 additions and 29 deletions

60
config.py Normal file
View file

@ -0,0 +1,60 @@
import os
import urllib.parse
from dotenv import load_dotenv
load_dotenv()
def quote(value):
return urllib.parse.quote_plus(value)
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = False
TESTING = False
DB_BACKEND = os.getenv('DB_BACKEND', 'sqlite').lower()
DB_WINDOWS_AUTH = os.getenv('DB_WINDOWS_AUTH', 'false').strip().lower() in ['true', '1', 'yes']
DB_USER = os.getenv('DB_USER', '')
DB_PASSWORD = os.getenv('DB_PASSWORD', '')
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '')
DB_NAME = os.getenv('DB_NAME', 'app.db') # default file for sqlite
SQLALCHEMY_DATABASE_URI = None # <-- initialize properly
if DB_BACKEND == 'mssql':
driver = os.getenv('DB_DRIVER', 'ODBC Driver 17 for SQL Server')
quoted_driver = quote(driver)
if DB_WINDOWS_AUTH:
SQLALCHEMY_DATABASE_URI = (
f"mssql+pyodbc://@{DB_HOST}/{DB_NAME}?driver={quoted_driver}&Trusted_Connection=yes"
)
else:
SQLALCHEMY_DATABASE_URI = (
f"mssql+pyodbc://{quote(DB_USER)}:{quote(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
f"?driver={quoted_driver}"
)
elif DB_BACKEND == 'postgres':
SQLALCHEMY_DATABASE_URI = (
f"postgresql://{quote(DB_USER)}:{quote(DB_PASSWORD)}@{DB_HOST}:{DB_PORT or '5432'}/{DB_NAME}"
)
elif DB_BACKEND in ['mariadb', 'mysql']:
SQLALCHEMY_DATABASE_URI = (
f"mysql+pymysql://{quote(DB_USER)}:{quote(DB_PASSWORD)}@{DB_HOST}:{DB_PORT or '3306'}/{DB_NAME}"
)
elif DB_BACKEND == 'sqlite':
if DB_NAME == ':memory:':
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
else:
SQLALCHEMY_DATABASE_URI = f"sqlite:///{DB_NAME}"
else:
raise ValueError(
f"Unsupported DB_BACKEND: {DB_BACKEND}. "
"Supported backends: mssql, postgres, mariadb, mysql, sqlite."
)