Refactor configuration; enhance quote function type hints, improve database URI setup for SQLite, and add BASE_DIR for better path management

This commit is contained in:
Yaro Kasear 2025-06-20 13:55:50 -05:00
parent e67ae63eb8
commit 142e909a88
2 changed files with 14 additions and 7 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
__pycache__/ __pycache__/
.venv/ .venv/
.env .env
app.db

View file

@ -4,8 +4,8 @@ from dotenv import load_dotenv
load_dotenv() load_dotenv()
def quote(value): def quote(value: str) -> str:
return urllib.parse.quote_plus(value) return urllib.parse.quote_plus(value or '')
class Config: class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_TRACK_MODIFICATIONS = False
@ -19,9 +19,11 @@ class Config:
DB_PASSWORD = os.getenv('DB_PASSWORD', '') DB_PASSWORD = os.getenv('DB_PASSWORD', '')
DB_HOST = os.getenv('DB_HOST', 'localhost') DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '') 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': if DB_BACKEND == 'mssql':
driver = os.getenv('DB_DRIVER', 'ODBC Driver 17 for SQL Server') driver = os.getenv('DB_DRIVER', 'ODBC Driver 17 for SQL Server')
@ -33,7 +35,7 @@ class Config:
) )
else: else:
SQLALCHEMY_DATABASE_URI = ( 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}" f"?driver={quoted_driver}"
) )
@ -51,10 +53,14 @@ class Config:
if DB_NAME == ':memory:': if DB_NAME == ':memory:':
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
else: 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: else:
raise ValueError( raise ValueError(
f"Unsupported DB_BACKEND: {DB_BACKEND}. " f"Unsupported DB_BACKEND: {DB_BACKEND}. "
"Supported backends: mssql, postgres, mariadb, mysql, sqlite." "Supported backends: mssql, postgres, mariadb, mysql, sqlite."
) )
# Optional: confirm config during development
print(f"Using database URI: {SQLALCHEMY_DATABASE_URI}")