Files
2026-10-29 10:53:32 +03:00

55 lines
1.7 KiB
Python

import os
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Settings:
host: str
port: int
env: str
log_level: str
shutdown_timeout: int
session_ttl_seconds: int
database_url: str
redis_url: str
history_cache: str
def _secret(file_var: str, value_var: str) -> str:
"""A *_FILE variable wins. The secret value is not logged."""
file_name = os.getenv(file_var, '').strip()
if file_name:
try:
value = Path(file_name).read_text(encoding='utf-8').strip()
except OSError:
raise RuntimeError('%s could not be read' % file_var) from None
if not value:
raise RuntimeError('%s is empty' % file_var)
return value
value = os.getenv(value_var, '').strip()
if not value:
raise RuntimeError('%s or %s is required' % (value_var, file_var))
return value
def _history_cache() -> str:
mode = os.getenv('HISTORY_CACHE', 'protected').strip().lower() or 'protected'
if mode not in ('protected', 'naive', 'off'):
raise RuntimeError('HISTORY_CACHE must be protected, naive or off')
return mode
def load_settings() -> Settings:
return Settings(
host=os.getenv('APP_HOST', '0.0.0.0'),
port=int(os.getenv('APP_PORT', '8080')),
env=os.getenv('APP_ENV', 'lab'),
log_level=os.getenv('LOG_LEVEL', 'info').lower(),
shutdown_timeout=int(os.getenv('SHUTDOWN_TIMEOUT_SECONDS', '5')),
session_ttl_seconds=int(os.getenv('SESSION_TTL_SECONDS', '3600')),
database_url=_secret('DATABASE_URL_FILE', 'DATABASE_URL'),
redis_url=_secret('CACHE_URL_FILE', 'REDIS_URL'),
history_cache=_history_cache(),
)