Исходная точка lab2: код из solution/bvt2302-bodanyuk лабы 1, коммит 472c1bd. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
"""Runtime configuration read from environment variables (12-factor style).
|
|
|
|
Every variable has a safe default, so `docker run` works from a clean clone
|
|
even without an .env file. Invalid values stop the process at startup with a
|
|
clear message instead of failing later under traffic.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
|
|
|
|
class ConfigError(ValueError):
|
|
pass
|
|
|
|
|
|
def _int(name: str, default: int, low: int, high: int) -> int:
|
|
raw = os.environ.get(name)
|
|
if raw is None or raw.strip() == "":
|
|
return default
|
|
try:
|
|
value = int(raw.strip())
|
|
except ValueError:
|
|
raise ConfigError(f"{name} must be an integer, got {raw!r}") from None
|
|
if not low <= value <= high:
|
|
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
|
|
return value
|
|
|
|
|
|
def _float(name: str, default: float, low: float, high: float) -> float:
|
|
raw = os.environ.get(name)
|
|
if raw is None or raw.strip() == "":
|
|
return default
|
|
try:
|
|
value = float(raw.strip())
|
|
except ValueError:
|
|
raise ConfigError(f"{name} must be a number, got {raw!r}") from None
|
|
if not low <= value <= high:
|
|
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
|
|
return value
|
|
|
|
|
|
def _bool(name: str, default: bool) -> bool:
|
|
raw = os.environ.get(name, "").strip().lower()
|
|
if raw == "":
|
|
return default
|
|
if raw not in {"true", "false", "1", "0"}:
|
|
raise ConfigError(f"{name} must be true/false, got {raw!r}")
|
|
return raw in {"true", "1"}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Settings:
|
|
host: str
|
|
port: int
|
|
env: str
|
|
log_level: str
|
|
shutdown_timeout: float
|
|
max_body_bytes: int
|
|
docs_enabled: bool = True
|
|
|
|
@classmethod
|
|
def from_env(cls) -> "Settings":
|
|
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
|
|
if log_level not in {"debug", "info", "warning", "error"}:
|
|
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
|
|
return cls(
|
|
host=os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0",
|
|
port=_int("APP_PORT", 8080, 1, 65535),
|
|
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
|
log_level=log_level,
|
|
# Docker sends SIGKILL 10 s after SIGTERM by default; finish earlier.
|
|
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 9.0),
|
|
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
|
|
docs_enabled=_bool("DOCS_ENABLED", True),
|
|
)
|