"""Application configuration. The whole persistence layer is driven by ``DATABASE_URL`` so that moving from the local SQLite file to MySQL is a configuration change, not a code change. Layout convention (shared with the other UNIS projects): / ├── app/ ← this package (backend) ├── data/ ← SQLite file, uploads, exports ├── web/ ← React front end (``web/dist`` is served when built) └── .env Relative paths in the configuration (``./data/hrms.db``, ``./data/uploads``) are resolved against the **project root**, not the current working directory, so ``uvicorn``/``alembic``/``pytest``/``scripts/*.py`` all agree on where the data lives no matter where they were launched from. """ from __future__ import annotations from functools import lru_cache from pathlib import Path from pydantic import Field, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict def _detect_project_root() -> Path: """Walk up from this file until the project root (pyproject + web) is found.""" here = Path(__file__).resolve() for candidate in here.parents: if (candidate / "pyproject.toml").is_file() and (candidate / "web").is_dir(): return candidate return Path.cwd() PROJECT_ROOT = _detect_project_root() def _anchor(path: Path) -> Path: """Make a possibly-relative path absolute against the project root.""" path = Path(path).expanduser() return path if path.is_absolute() else (PROJECT_ROOT / path).resolve() class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=PROJECT_ROOT / ".env", env_file_encoding="utf-8", extra="ignore" ) app_name: str = "UNIS 人力资源管理系统" api_prefix: str = "/api/v1" version: str = "2.0.0" debug: bool = True secret_key: str = "dev-secret-key-change-me" access_token_minutes: int = 120 refresh_token_days: int = 14 database_url: str = "sqlite+aiosqlite:///./data/hrms.db" auto_create_schema: bool = True auto_seed: bool = False upload_dir: Path = Path("./data/uploads") max_upload_mb: int = 20 cors_origins: list[str] = Field( default_factory=lambda: ["http://localhost:5173", "http://127.0.0.1:5173"] ) # Serve the built front end (``web/dist``) from the API process, so a single # container exposes the whole product. Silently ignored when not built. serve_web_dist: bool = True web_dist_dir: Path = Path("./web/dist") # ---- normalisation --------------------------------------------------- @field_validator("upload_dir", "web_dist_dir", mode="after") @classmethod def _absolute_dirs(cls, value: Path) -> Path: return _anchor(value) @field_validator("database_url", mode="after") @classmethod def _absolute_sqlite(cls, value: str) -> str: """``sqlite+aiosqlite:///./data/hrms.db`` → absolute path (CWD independent).""" prefix, sep, rest = value.partition(":///") if not sep or not prefix.startswith("sqlite") or rest.startswith(("/", ":memory:")): return value return f"{prefix}:///{_anchor(Path(rest))}" # ---- helpers --------------------------------------------------------- @property def project_root(self) -> Path: return PROJECT_ROOT @property def data_dir(self) -> Path: return _anchor(Path("data")) @property def sync_database_url(self) -> str: """Synchronous DSN, used by Alembic migrations.""" return ( self.database_url.replace("+aiosqlite", "") .replace("+aiomysql", "+pymysql") .replace("+asyncmy", "+pymysql") ) @property def is_sqlite(self) -> bool: return self.database_url.startswith("sqlite") @lru_cache def get_settings() -> Settings: return Settings() settings = get_settings()