| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import os
- from pathlib import Path
- def _find_config_file():
- """根据环境变量 APP_ENV 查找对应的配置文件
- 支持: APP_ENV=local/dev/test/uat/prod -> .env.local / .env.dev / ...
- 默认: local
- 查找路径优先级:
- 1. {package}/config/ (源码路径)
- 2. /app/standards_service/config/ (Docker COPY 路径)
- 3. /app/config/ (Docker volume 挂载路径)
- 4. {cwd}/config/ (工作目录)
- """
- env = os.environ.get("APP_ENV", "local")
- filename = f".env.{env}"
- candidates = [
- Path(__file__).resolve().parent.parent / "config" / filename,
- Path("/app/standards_service/config") / filename,
- Path("/app/config") / filename,
- Path(os.getcwd()) / "config" / filename,
- ]
- for cfg in candidates:
- if cfg.exists():
- return cfg
- return candidates[0]
- def _load_env_file(path):
- """从 .env 文件中加载键值对到 os.environ(不覆盖已有变量)。"""
- if not path.exists():
- return
- with open(path, encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- if "=" in line:
- key, _, value = line.partition("=")
- key = key.strip()
- value = value.strip().strip('"').strip("'")
- if key and key not in os.environ:
- os.environ[key] = value
- def load_config():
- """加载配置,返回配置文件路径。"""
- config_path = _find_config_file()
- _load_env_file(config_path)
- return config_path
|