Files
shared/packages/python-backend/src/shared_backend/config.py
T
Gabriel20xx c94f749430 fix: reformat config.py to match its declared 100-column line length
One line was wrapped as if for an 88-column budget, violating the
100-column ruff line-length this package declares in its own
pyproject.toml - ruff format (which respects that nested config)
correctly flagged it as unformatted.
2026-08-19 13:04:17 +02:00

48 lines
1.6 KiB
Python

"""Dependency-free environment configuration helpers."""
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Mapping
def _int_value(env: Mapping[str, str], key: str, fallback: int, minimum: int) -> int:
try:
value = int(env.get(key, ""))
except (TypeError, ValueError):
return fallback
return value if value >= minimum else fallback
def database_url_from_env(env: Mapping[str, str] | None = None) -> str:
source = os.environ if env is None else env
value = str(source.get("DATABASE_URL", "")).strip()
if not value:
raise RuntimeError("DATABASE_URL environment variable is required")
return value
@dataclass(frozen=True, slots=True)
class DatabaseConfig:
dsn: str
min_size: int = 0
max_size: int = 20
timeout: float = 5.0
command_timeout: float = 15.0
@classmethod
def from_env(cls, env: Mapping[str, str] | None = None) -> "DatabaseConfig":
source = os.environ if env is None else env
max_size = _int_value(source, "DATABASE_MAX_CONNS", 20, 1)
min_size = _int_value(source, "DATABASE_MIN_CONNS", 0, 0)
if min_size > max_size:
raise ValueError("DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS")
return cls(
dsn=database_url_from_env(source),
min_size=min_size,
max_size=max_size,
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
command_timeout=float(_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)),
)