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

3
.gitignore vendored
View file

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

View file

@ -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}")