Files
quiz/app/config.py
2026-05-02 02:59:34 +08:00

48 lines
1.4 KiB
Python

"""Application configuration."""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
def load_dotenv(path: str | Path = ".env") -> None:
env_path = Path(path)
if not env_path.exists():
return
for raw_line in env_path.read_text().splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
@dataclass(slots=True)
class Settings:
db_path: str = "./quiz.db"
secret_key: str | None = None
admin_password: str | None = None
host: str = "127.0.0.1"
port: int = 8001
public_url: str = "https://quiz.ahkhan.me"
log_level: str = "INFO"
@classmethod
def from_env(cls) -> "Settings":
load_dotenv()
return cls(
db_path=os.getenv("QUIZ_DB_PATH", "./quiz.db"),
secret_key=os.getenv("QUIZ_SECRET_KEY"),
admin_password=os.getenv("QUIZ_ADMIN_PASSWORD"),
host=os.getenv("QUIZ_HOST", "127.0.0.1"),
port=int(os.getenv("QUIZ_PORT", "8001")),
public_url=os.getenv("QUIZ_PUBLIC_URL", "https://quiz.ahkhan.me").rstrip("/"),
log_level=os.getenv("QUIZ_LOG_LEVEL", "INFO"),
)
@property
def secure_cookies(self) -> bool:
return self.public_url.startswith("https://")