From 142e909a8812dce2606cea4020eb6122b3eabb4f Mon Sep 17 00:00:00 2001 From: Yaro Kasear Date: Fri, 20 Jun 2025 13:55:50 -0500 Subject: [PATCH] Refactor configuration; enhance quote function type hints, improve database URI setup for SQLite, and add BASE_DIR for better path management --- .gitignore | 3 ++- config.py | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 099fcce..6d493b7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__/ .venv/ -.env \ No newline at end of file +.env +app.db \ No newline at end of file diff --git a/config.py b/config.py index 012c37e..0372d87 100644 --- a/config.py +++ b/config.py @@ -4,8 +4,8 @@ from dotenv import load_dotenv load_dotenv() -def quote(value): - return urllib.parse.quote_plus(value) +def quote(value: str) -> str: + return urllib.parse.quote_plus(value or '') class Config: SQLALCHEMY_TRACK_MODIFICATIONS = False @@ -19,9 +19,11 @@ class Config: 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 + DB_NAME = os.getenv('DB_NAME', 'app.db') # default SQLite filename - SQLALCHEMY_DATABASE_URI = None # <-- initialize properly + BASE_DIR = os.path.abspath(os.path.dirname(__file__)) + + SQLALCHEMY_DATABASE_URI = None # This will definitely be set below if DB_BACKEND == 'mssql': driver = os.getenv('DB_DRIVER', 'ODBC Driver 17 for SQL Server') @@ -33,7 +35,7 @@ class Config: ) else: SQLALCHEMY_DATABASE_URI = ( - f"mssql+pyodbc://{quote(DB_USER)}:{quote(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}" + f"mssql+pyodbc://{quote(DB_USER)}:{quote(DB_PASSWORD)}@{DB_HOST}:{DB_PORT or '1433'}/{DB_NAME}" f"?driver={quoted_driver}" ) @@ -51,10 +53,14 @@ class Config: if DB_NAME == ':memory:': SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' else: - SQLALCHEMY_DATABASE_URI = f"sqlite:///{DB_NAME}" + full_path = os.path.join(BASE_DIR, DB_NAME) + SQLALCHEMY_DATABASE_URI = f"sqlite:///{full_path}" else: raise ValueError( f"Unsupported DB_BACKEND: {DB_BACKEND}. " "Supported backends: mssql, postgres, mariadb, mysql, sqlite." ) + + # Optional: confirm config during development + print(f"Using database URI: {SQLALCHEMY_DATABASE_URI}")