yaml_config_loader.py
1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
import yaml
def resolve_config_path(config_path=None):
"""解析配置文件路径,支持 docker 与本地默认路径。"""
if config_path:
return config_path
docker_default = '/app/config.yaml'
local_default = os.path.join('config', 'config.yaml')
if os.path.exists(docker_default):
return docker_default
return local_default
def load_db_configs(config_path=None, required_keys=None):
"""从 YAML 文件中读取数据库连接配置。"""
required_keys = required_keys or []
resolved_path = resolve_config_path(config_path)
if not os.path.exists(resolved_path):
raise FileNotFoundError(f'配置文件不存在: {resolved_path}')
with open(resolved_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
raise ValueError('配置文件格式错误,根节点必须为字典')
missing_keys = [key for key in required_keys if key not in data]
if missing_keys:
raise KeyError(f'配置缺少必要节点: {", ".join(missing_keys)}')
return data