config_loader.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. from pathlib import Path
  3. def _find_config_file():
  4. """根据环境变量 APP_ENV 查找对应的配置文件
  5. 支持: APP_ENV=local/dev/test/uat/prod -> .env.local / .env.dev / ...
  6. 默认: local
  7. 查找路径优先级:
  8. 1. {package}/config/ (源码路径)
  9. 2. /app/standards_service/config/ (Docker COPY 路径)
  10. 3. /app/config/ (Docker volume 挂载路径)
  11. 4. {cwd}/config/ (工作目录)
  12. """
  13. env = os.environ.get("APP_ENV", "local")
  14. filename = f".env.{env}"
  15. candidates = [
  16. Path(__file__).resolve().parent.parent / "config" / filename,
  17. Path("/app/standards_service/config") / filename,
  18. Path("/app/config") / filename,
  19. Path(os.getcwd()) / "config" / filename,
  20. ]
  21. for cfg in candidates:
  22. if cfg.exists():
  23. return cfg
  24. return candidates[0]
  25. def _load_env_file(path):
  26. """从 .env 文件中加载键值对到 os.environ(不覆盖已有变量)。"""
  27. if not path.exists():
  28. return
  29. with open(path, encoding="utf-8") as f:
  30. for line in f:
  31. line = line.strip()
  32. if not line or line.startswith("#"):
  33. continue
  34. if "=" in line:
  35. key, _, value = line.partition("=")
  36. key = key.strip()
  37. value = value.strip().strip('"').strip("'")
  38. if key and key not in os.environ:
  39. os.environ[key] = value
  40. def load_config():
  41. """加载配置,返回配置文件路径。"""
  42. config_path = _find_config_file()
  43. _load_env_file(config_path)
  44. return config_path