Files
web/app/config.py
2026-11-06 11:42:34 -05:00

73 lines
2.4 KiB
Python

"""Settings, read from environment variables (or a local .env file).
Every setting has a safe local default, so `uvicorn app.main:app` works with no
configuration: it uses a SQLite file next to this folder and no password.
In production you set DATABASE_URL, SECRET_KEY and DASHBOARD_PASSWORD on the host.
"""
from functools import lru_cache
from pathlib import Path
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
WEB_DIR = Path(__file__).resolve().parent.parent
DEV_SECRET = "dev-only-secret-change-me"
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=WEB_DIR / ".env", extra="ignore")
# "development" or "production". Production turns on secure cookies and
# warns loudly about missing secrets.
app_env: str = "development"
# Postgres in production (Neon, Supabase, Render...), SQLite locally.
database_url: str = f"sqlite:///{(WEB_DIR / 'mamadachi.db').as_posix()}"
# Signs the login cookie. Any long random string; keep it secret.
secret_key: str = DEV_SECRET
# One shared password for the dashboard. Empty = no login (local dev only!).
dashboard_password: str = ""
# Timezone used until the parent picks one on the Settings page.
default_timezone: str = "UTC"
# Run database migrations when the app starts. Leave on unless you run
# `alembic upgrade head` yourself as a deploy step.
auto_migrate: bool = True
# Production refuses to start on SQLite, because most hosts wipe the disk
# on every deploy. Set true only if the file sits on a persistent volume.
allow_sqlite_in_production: bool = False
log_level: str = "INFO"
@field_validator("database_url")
@classmethod
def _normalise_db_url(cls, v: str) -> str:
# Hosts hand out "postgres://..." or "postgresql://..."; SQLAlchemy needs
# to be told to use the psycopg (v3) driver.
for prefix in ("postgres://", "postgresql://"):
if v.startswith(prefix):
return "postgresql+psycopg://" + v[len(prefix):]
return v
@property
def is_production(self) -> bool:
return self.app_env.lower() in {"prod", "production"}
@property
def is_sqlite(self) -> bool:
return self.database_url.startswith("sqlite")
@property
def login_required(self) -> bool:
return bool(self.dashboard_password)
@lru_cache
def get_settings() -> Settings:
return Settings()