fix: normalize host runtime service endpoints

This commit is contained in:
2026-04-09 19:47:17 +02:00
parent e5c8ac7592
commit 0cd02513d5
3 changed files with 100 additions and 6 deletions
+56 -6
View File
@@ -1,8 +1,57 @@
from pydantic_settings import BaseSettings
import os
from typing import Optional
from urllib.parse import urlsplit, urlunsplit
from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
_DOCKER_SERVICE_ALIASES = {"postgres", "redis", "minio"}
def _is_running_in_container() -> bool:
if os.path.exists("/.dockerenv"):
return True
try:
with open("/proc/1/cgroup", "r", encoding="utf-8") as handle:
return "docker" in handle.read() or "containerd" in handle.read()
except OSError:
return False
def _normalize_service_host(host: str) -> str:
if _is_running_in_container():
return host
return "localhost" if host in _DOCKER_SERVICE_ALIASES else host
def _normalize_service_url(url: str) -> str:
parsed = urlsplit(url)
if not parsed.hostname:
return url
normalized_host = _normalize_service_host(parsed.hostname)
if normalized_host == parsed.hostname:
return url
netloc = normalized_host
if parsed.username:
auth = parsed.username
if parsed.password:
auth = f"{auth}:{parsed.password}"
netloc = f"{auth}@{netloc}"
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
case_sensitive=False,
extra="ignore",
)
# Database
postgres_db: str = "hartomat"
postgres_user: str = "hartomat"
@@ -27,6 +76,12 @@ class Settings(BaseSettings):
# Redis / Celery
redis_url: str = "redis://localhost:6379/0"
@model_validator(mode="after")
def normalize_runtime_hosts(self) -> "Settings":
self.postgres_host = _normalize_service_host(self.postgres_host)
self.redis_url = _normalize_service_url(self.redis_url)
return self
# JWT
jwt_secret_key: str = "changeme"
jwt_algorithm: str = "HS256"
@@ -42,9 +97,4 @@ class Settings(BaseSettings):
upload_dir: str = "/app/uploads"
max_upload_size_mb: int = 500
class Config:
env_file = ".env"
case_sensitive = False
settings = Settings()