296 lines
8.0 KiB
Python
296 lines
8.0 KiB
Python
"""
|
||
配置使用示例
|
||
|
||
展示如何在项目中使用统一的配置加载系统。
|
||
|
||
配置优先级(从高到低):
|
||
1. 环境变量(.env 文件或系统环境变量)
|
||
2. config.local.yaml(本地覆盖配置,不提交到版本库)
|
||
3. config.yaml(主配置文件)
|
||
"""
|
||
|
||
# ==============================================================================
|
||
# 示例 1: 读取环境变量(推荐用于敏感信息)
|
||
# ==============================================================================
|
||
|
||
from env_loader import get_env, get_env_bool, get_env_int, check_required_env_vars
|
||
|
||
# 读取 API 密钥(必需)
|
||
gemini_api_key = get_env(
|
||
"GEMINI_API_KEY",
|
||
required=True,
|
||
hint="See .env.example for instructions on obtaining the API key"
|
||
)
|
||
|
||
# 读取 API 密钥(可选,有默认值)
|
||
azure_api_key = get_env("AZURE_API_KEY", default="")
|
||
|
||
# 读取布尔配置
|
||
debug_mode = get_env_bool("DEBUG", default=False)
|
||
|
||
# 读取整数配置
|
||
timeout = get_env_int("TIMEOUT", default=30)
|
||
|
||
# 批量检查必需的环境变量
|
||
missing_vars = check_required_env_vars([
|
||
"GEMINI_API_KEY",
|
||
"AZURE_API_KEY",
|
||
])
|
||
|
||
if missing_vars:
|
||
from env_loader import print_env_setup_guide
|
||
print(f"Missing required environment variables: {', '.join(missing_vars)}")
|
||
print_env_setup_guide()
|
||
raise ValueError("Missing required environment variables")
|
||
|
||
|
||
# ==============================================================================
|
||
# 示例 2: 读取配置文件(推荐用于非敏感配置)
|
||
# ==============================================================================
|
||
|
||
from config_loader import load_config
|
||
|
||
# 加载配置(自动根据 current_env.txt 选择环境)
|
||
config = load_config()
|
||
|
||
# 读取配置项(使用 get 方法提供默认值)
|
||
log_level = config.get("logging", {}).get("level", "INFO")
|
||
output_dir = config.get("output", {}).get("base_dir", "./output")
|
||
redis_host = config.get("redis", {}).get("host", "localhost")
|
||
|
||
# 读取嵌套配置
|
||
mumu_manager_path = config.get("mumu", {}).get("manager_path", "")
|
||
|
||
# 读取环境变量引用(配置文件中使用 ${ENV_VAR_NAME} 格式)
|
||
# 例如在 config.yaml 中:
|
||
# notifications:
|
||
# wechat:
|
||
# user1: "${WECHAT_TOKEN_USER1}"
|
||
wechat_tokens = config.get("notifications", {}).get("wechat", {})
|
||
|
||
|
||
# ==============================================================================
|
||
# 示例 3: 完整的配置初始化函数
|
||
# ==============================================================================
|
||
|
||
import logging
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
def initialize_config():
|
||
"""
|
||
初始化项目配置
|
||
|
||
配置加载顺序:
|
||
1. 环境变量(.env)- 用于敏感信息
|
||
2. config.yaml(主配置)
|
||
3. config.local.yaml(本地覆盖配置,不提交到版本库)
|
||
|
||
Returns:
|
||
dict: 完整的配置字典
|
||
"""
|
||
# 1. 自动加载 .env 文件(env_loader 模块导入时自动执行)
|
||
# 不需要手动调用 load_dotenv()
|
||
|
||
# 2. 检查必需的环境变量
|
||
required_env_vars = [
|
||
"GEMINI_API_KEY", # 至少需要一个 AI 服务的 API Key
|
||
# 可根据实际需求添加更多必需变量
|
||
]
|
||
|
||
# 检查是否至少有一个 AI 服务的 API Key
|
||
ai_service_keys = [
|
||
"GEMINI_API_KEY",
|
||
"AZURE_API_KEY",
|
||
"QWEN_API_KEY",
|
||
"GLM_API_KEY",
|
||
]
|
||
|
||
has_ai_key = any(get_env(key) for key in ai_service_keys)
|
||
|
||
if not has_ai_key:
|
||
logger.error("No AI service API key found in environment variables")
|
||
from env_loader import print_env_setup_guide
|
||
print_env_setup_guide()
|
||
raise ValueError(
|
||
f"At least one AI service API key is required: {', '.join(ai_service_keys)}"
|
||
)
|
||
|
||
# 3. 加载配置文件
|
||
try:
|
||
config = load_config()
|
||
logger.info(f"Loaded configuration for environment: {config.get('environment', {}).get('name', 'unknown')}")
|
||
except FileNotFoundError as e:
|
||
logger.error(f"Configuration file not found: {e}")
|
||
raise
|
||
|
||
# 4. 验证配置完整性(可选)
|
||
validate_config(config)
|
||
|
||
return config
|
||
|
||
|
||
def validate_config(config: dict):
|
||
"""
|
||
验证配置完整性
|
||
|
||
Args:
|
||
config: 配置字典
|
||
|
||
Raises:
|
||
ValueError: 配置不完整或格式错误时
|
||
"""
|
||
# 验证必需的配置项
|
||
required_sections = ["output", "device", "logging"]
|
||
|
||
for section in required_sections:
|
||
if section not in config:
|
||
raise ValueError(f"Missing required config section: {section}")
|
||
|
||
# 验证输出目录配置
|
||
output_config = config.get("output", {})
|
||
if "base_dir" not in output_config:
|
||
raise ValueError("Missing required config: output.base_dir")
|
||
|
||
# 验证日志级别
|
||
log_level = config.get("logging", {}).get("level", "INFO")
|
||
valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
|
||
if log_level not in valid_levels:
|
||
logger.warning(
|
||
f"Invalid log level '{log_level}', using 'INFO'. "
|
||
f"Valid levels: {', '.join(valid_levels)}"
|
||
)
|
||
|
||
logger.info("Configuration validation passed")
|
||
|
||
|
||
# ==============================================================================
|
||
# 示例 4: 在实际项目中使用
|
||
# ==============================================================================
|
||
|
||
def main():
|
||
"""主函数示例"""
|
||
# 初始化配置
|
||
config = initialize_config()
|
||
|
||
# 读取环境变量
|
||
gemini_key = get_env("GEMINI_API_KEY", required=True)
|
||
|
||
# 读取配置文件中的设置
|
||
output_dir = config.get("output", {}).get("base_dir", "./output")
|
||
log_level = config.get("logging", {}).get("level", "INFO")
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=getattr(logging, log_level),
|
||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||
)
|
||
|
||
logger.info(f"Application started with config: {config.get('environment', {}).get('name', 'unknown')}")
|
||
logger.info(f"Output directory: {output_dir}")
|
||
|
||
# 业务逻辑...
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
|
||
|
||
# ==============================================================================
|
||
# 迁移指南:从硬编码配置迁移到统一配置
|
||
# ==============================================================================
|
||
|
||
"""
|
||
迁移步骤:
|
||
|
||
1. 将硬编码的敏感信息移到 .env 文件:
|
||
|
||
旧代码:
|
||
```python
|
||
GEMINI_API_KEY = "AQ.Ab8RN6INSIgaGdgj5hmmYmi35QLw6K3likBz2bP37_I_F6V5aQ"
|
||
```
|
||
|
||
新代码:
|
||
```python
|
||
from env_loader import get_env
|
||
GEMINI_API_KEY = get_env("GEMINI_API_KEY", required=True)
|
||
```
|
||
|
||
.env 文件:
|
||
```
|
||
GEMINI_API_KEY=AQ.Ab8RN6INSIgaGdgj5hmmYmi35QLw6K3likBz2bP37_I_F6V5aQ
|
||
```
|
||
|
||
|
||
2. 将非敏感配置移到 config.yaml:
|
||
|
||
旧代码:
|
||
```python
|
||
OUTPUT_DIR = "./output"
|
||
LOG_LEVEL = "INFO"
|
||
TIMEOUT = 30
|
||
```
|
||
|
||
新代码:
|
||
```python
|
||
from config_loader import load_config
|
||
config = load_config()
|
||
OUTPUT_DIR = config.get("output", {}).get("base_dir", "./output")
|
||
LOG_LEVEL = config.get("logging", {}).get("level", "INFO")
|
||
TIMEOUT = config.get("execution", {}).get("timeout", 30)
|
||
```
|
||
|
||
config.yaml:
|
||
```yaml
|
||
output:
|
||
base_dir: ./output
|
||
logging:
|
||
level: INFO
|
||
execution:
|
||
timeout: 30
|
||
```
|
||
|
||
|
||
3. 在配置文件中引用环境变量:
|
||
|
||
config/prod.yaml:
|
||
```yaml
|
||
notifications:
|
||
wechat:
|
||
yfz: "${WECHAT_TOKEN_YFZ}" # 从环境变量读取
|
||
```
|
||
|
||
.env 文件:
|
||
```
|
||
WECHAT_TOKEN_YFZ=your_token_here
|
||
```
|
||
|
||
|
||
4. 向后兼容处理(配置文件不存在时给出提示):
|
||
|
||
```python
|
||
from config_loader import load_config
|
||
|
||
try:
|
||
config = load_config()
|
||
except FileNotFoundError as e:
|
||
print(f"Configuration file not found: {e}")
|
||
print("Please set up the configuration files in the config/ directory")
|
||
# 使用默认配置或退出
|
||
raise
|
||
```
|
||
|
||
|
||
5. 本地开发配置覆盖:
|
||
|
||
创建 config/local.yaml(不会提交到版本库):
|
||
```yaml
|
||
# 本地开发覆盖配置
|
||
logging:
|
||
level: DEBUG # 覆盖生产环境的 INFO
|
||
output:
|
||
base_dir: D:/local_output # 本地路径
|
||
```
|
||
"""
|