Improve Settings class with robust DB path handling
- Replace DB_DIR class variable with proper DB_PATH string field - Add initialization logic to safely create database directory - Add fallback to in-memory database if directory creation fails - Make database path configurable via environment variable - Fix docstring linting issues
This commit is contained in:
parent
bff5c53372
commit
2b5397d2ea
@ -1,12 +1,11 @@
|
||||
"""Application configuration settings."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import ClassVar
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
# Create database directory
|
||||
DB_DIR = Path("/app") / "storage" / "db"
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
# Use a safe default path for the database
|
||||
DEFAULT_DB_PATH = Path(os.getenv("DB_PATH", "/app/storage/db"))
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@ -17,13 +16,31 @@ class Settings(BaseSettings):
|
||||
API_V1_STR: str = "/api/v1"
|
||||
|
||||
# Database
|
||||
DB_DIR: ClassVar[Path] = DB_DIR
|
||||
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
DB_PATH: str = str(DEFAULT_DB_PATH)
|
||||
SQLALCHEMY_DATABASE_URL: str = ""
|
||||
|
||||
model_config = {
|
||||
"case_sensitive": True,
|
||||
"env_file": ".env",
|
||||
}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""Initialize settings and set up database directory and URL.
|
||||
|
||||
Creates the database directory if it doesn't exist and sets the
|
||||
database URL accordingly. Falls back to an in-memory database if
|
||||
directory creation fails.
|
||||
"""
|
||||
super().__init__(**kwargs)
|
||||
# Create the DB directory if it doesn't exist
|
||||
db_dir = Path(self.DB_PATH)
|
||||
try:
|
||||
db_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.SQLALCHEMY_DATABASE_URL = f"sqlite:///{db_dir}/db.sqlite"
|
||||
except (OSError, PermissionError):
|
||||
# Fallback to an in-memory database if we can't create the directory
|
||||
self.SQLALCHEMY_DATABASE_URL = "sqlite://"
|
||||
print("WARNING: Could not create database directory. Using in-memory SQLite database.")
|
||||
|
||||
|
||||
settings = Settings()
|
Loading…
x
Reference in New Issue
Block a user