# -*- coding: utf-8 -*- """ @Module: common.env @FileName: env.py @Author: 小布丁 @Description: app 蓝图版专属 .env 加载器。 与其它方向(webhost/controlplane)的 env 互不干扰:本模块只加载 /.env,即使进程 cwd 不在 app 目录也能读到;且不覆盖已存在的环境变量。 所有 app 模块统一改用 load_app_env() 替代裸 load_dotenv()。 """ import os from pathlib import Path # app/.env 固定定位:本文件(app/common/env.py)上两级即 app 根 APP_ENV_PATH = Path(__file__).resolve().parent.parent / ".env" def load_app_env(path: str | os.PathLike = APP_ENV_PATH) -> None: """幂等加载 app/.env(默认不覆盖已设环境变量)。""" env_path = Path(path) if not env_path.is_file(): return try: from dotenv import load_dotenv load_dotenv(str(env_path), override=False) return except ImportError: pass # python-dotenv 缺失时手动解析,保证零第三方依赖可用 for line in env_path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") key = key.strip() value = value.strip().strip("\"'") if key and value and key not in os.environ: os.environ[key] = value