forked from mtusi2026/mtusi2026lab2
108 lines
4.1 KiB
Python
108 lines
4.1 KiB
Python
"""Настройки приложения из переменных окружения."""
|
||
|
||
import os
|
||
from dataclasses import dataclass
|
||
from typing import Mapping, Optional
|
||
|
||
LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Settings:
|
||
"""Неизменяемый набор настроек."""
|
||
|
||
host: str
|
||
port: int
|
||
env: str
|
||
log_level: str
|
||
database_url: str
|
||
session_ttl_seconds: int
|
||
session_store: str
|
||
db_pool_size: int
|
||
db_max_overflow: int
|
||
db_pool_timeout: int
|
||
db_startup_wait_seconds: int
|
||
cache_url: str
|
||
cache_ttl_seconds: int
|
||
cache_timeout_ms: int
|
||
cache_retry_seconds: int
|
||
|
||
@classmethod
|
||
def from_env(cls, environ: Optional[Mapping[str, str]] = None) -> "Settings":
|
||
"""Собрать и проверить настройки; при ошибке ValueError с описанием."""
|
||
source = os.environ if environ is None else environ
|
||
|
||
def get(name: str, default: str) -> str:
|
||
value = source.get(name)
|
||
if value is None or value.strip() == "":
|
||
return default
|
||
return value.strip()
|
||
|
||
def get_int(name: str, default: int, low: int, high: int) -> int:
|
||
text = get(name, str(default))
|
||
if not text.isdigit() or not (low <= int(text) <= high):
|
||
raise ValueError(
|
||
"%s должен быть числом от %d до %d" % (name, low, high)
|
||
)
|
||
return int(text)
|
||
|
||
log_level = get("LOG_LEVEL", "INFO").upper()
|
||
if log_level not in LOG_LEVELS:
|
||
raise ValueError(
|
||
"LOG_LEVEL должен быть одним из %s" % ", ".join(LOG_LEVELS)
|
||
)
|
||
|
||
session_store = get("SESSION_STORE", "postgres")
|
||
if session_store != "postgres":
|
||
raise ValueError(
|
||
"SESSION_STORE: источник истины сессий -- только postgres "
|
||
"(Redis -- кэш, задаётся CACHE_URL)"
|
||
)
|
||
|
||
database_url = _read_database_url(source)
|
||
if not database_url.startswith("postgresql+asyncpg://"):
|
||
raise ValueError("DATABASE_URL должен начинаться с postgresql+asyncpg://")
|
||
|
||
return cls(
|
||
host=get("APP_HOST", "127.0.0.1"),
|
||
port=get_int("APP_PORT", 8080, 1, 65535),
|
||
env=get("APP_ENV", "lab"),
|
||
log_level=log_level,
|
||
database_url=database_url,
|
||
session_ttl_seconds=get_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
|
||
session_store=session_store,
|
||
db_pool_size=get_int("DB_POOL_SIZE", 5, 1, 50),
|
||
db_max_overflow=get_int("DB_MAX_OVERFLOW", 5, 0, 50),
|
||
db_pool_timeout=get_int("DB_POOL_TIMEOUT", 5, 1, 60),
|
||
db_startup_wait_seconds=get_int("DB_STARTUP_WAIT_SECONDS", 30, 0, 300),
|
||
cache_url=_read_cache_url(source),
|
||
cache_ttl_seconds=get_int("CACHE_TTL_SECONDS", 60, 1, 3600),
|
||
cache_timeout_ms=get_int("CACHE_TIMEOUT_MS", 300, 10, 5000),
|
||
cache_retry_seconds=get_int("CACHE_RETRY_SECONDS", 5, 0, 300),
|
||
)
|
||
|
||
|
||
def _read_database_url(source: Mapping[str, str]) -> str:
|
||
"""Адрес БД из DATABASE_URL_FILE или DATABASE_URL."""
|
||
path = source.get("DATABASE_URL_FILE", "").strip()
|
||
if path:
|
||
with open(path, encoding="utf-8") as handle:
|
||
return handle.read().strip()
|
||
value = source.get("DATABASE_URL", "").strip()
|
||
if not value:
|
||
raise ValueError("Не задан DATABASE_URL (или DATABASE_URL_FILE)")
|
||
return value
|
||
|
||
|
||
def _read_cache_url(source: Mapping[str, str]) -> str:
|
||
"""Адрес Redis из CACHE_URL_FILE или CACHE_URL; пустая строка -- кэш выключен."""
|
||
path = source.get("CACHE_URL_FILE", "").strip()
|
||
if path:
|
||
with open(path, encoding="utf-8") as handle:
|
||
value = handle.read().strip()
|
||
else:
|
||
value = source.get("CACHE_URL", "").strip()
|
||
if value and not value.startswith(("redis://", "rediss://")):
|
||
raise ValueError("CACHE_URL должен начинаться с redis:// или rediss://")
|
||
return value
|