api_config.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """API 配置模型。
  2. 集中管理服务运行参数,并提供从环境变量读取配置的能力。
  3. """
  4. import os
  5. from dataclasses import dataclass
  6. from depth_common import Settings
  7. @dataclass(frozen=True)
  8. class ApiConfig:
  9. """服务配置。
  10. 字段说明:
  11. - `sample_count`: 单次测量期望采样帧数;
  12. - `frame_timeout_ms`: 每次等待帧的超时时间;
  13. - `sample_timeout_sec`: 整体采样总超时;
  14. - `max_saved_images`: 本地最多保留图片数量;
  15. - `request_log_*`: 请求日志相关限制;
  16. - `api_host` / `api_port`: API 监听地址;
  17. - `settings`: 深度处理参数集合。
  18. """
  19. sample_count: int
  20. frame_timeout_ms: int
  21. sample_timeout_sec: int
  22. max_saved_images: int
  23. request_log_max_len: int
  24. request_log_max_bytes: int
  25. request_log_backup_count: int
  26. api_host: str
  27. api_port: int
  28. settings: Settings
  29. @classmethod
  30. def from_env(cls) -> "ApiConfig":
  31. """从环境变量构建配置,未设置时使用默认值。"""
  32. return cls(
  33. sample_count=int(os.getenv("SAMPLE_COUNT", "10")),
  34. frame_timeout_ms=int(os.getenv("FRAME_TIMEOUT_MS", "200")),
  35. sample_timeout_sec=int(os.getenv("SAMPLE_TIMEOUT_SEC", "8")),
  36. max_saved_images=int(os.getenv("MAX_SAVED_IMAGES", "1000")),
  37. request_log_max_len=int(os.getenv("REQUEST_LOG_MAX_LEN", "1000")),
  38. request_log_max_bytes=int(os.getenv("REQUEST_LOG_MAX_BYTES", str(20 * 1024 * 1024))),
  39. request_log_backup_count=int(os.getenv("REQUEST_LOG_BACKUP_COUNT", "10")),
  40. api_host=os.getenv("API_HOST", "0.0.0.0"),
  41. api_port=int(os.getenv("API_PORT", "8080")),
  42. settings=Settings.from_env(),
  43. )