yaml_config_loader.py 1.09 KB
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