Files
mtusi2026lab3/app/config.py
T

50 lines
1.6 KiB
Python

import os
import socket
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
idempotency_ttl_seconds: int
database_url: str
instance_id: 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 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')),
idempotency_ttl_seconds=int(os.getenv('IDEMPOTENCY_TTL_SECONDS', '86400')),
database_url=_secret('DATABASE_URL_FILE', 'DATABASE_URL'),
# Docker sets the hostname to the short container ID, which stop-one.sh maps back to a container.
instance_id=os.getenv('INSTANCE_ID', '').strip() or socket.gethostname(),
)