加载 .env 文件到 os.environ(不覆盖已有的系统环境变量)
()
| 11 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 12 | |
| 13 | def _load_dotenv(): |
| 14 | """加载 .env 文件到 os.environ(不覆盖已有的系统环境变量)""" |
| 15 | env_file = os.path.join(BASE_DIR, ".env") |
| 16 | if not os.path.exists(env_file): |
| 17 | return |
| 18 | had_key = "DEEPSEEK_API_KEY" in os.environ |
| 19 | with open(env_file, "r", encoding="utf-8") as f: |
| 20 | for line in f: |
| 21 | line = line.strip() |
| 22 | if not line or line.startswith("#") or "=" not in line: |
| 23 | continue |
| 24 | key, _, val = line.partition("=") |
| 25 | key, val = key.strip(), val.strip().strip("\"'") |
| 26 | if key and key not in os.environ: |
| 27 | os.environ[key] = val |
| 28 | if "DEEPSEEK_API_KEY" in os.environ: |
| 29 | os.environ["_DEEPSEEK_KEY_SOURCE"] = "sys" if had_key else "dotenv" |
| 30 | |
| 31 | def _ensure_api_key(): |
| 32 | """确保 DEEPSEEK_API_KEY 已设置:系统环境变量 > .env > 交互输入""" |