79 lines
2.4 KiB
Python
79 lines
2.4 KiB
Python
# -*- encoding=utf8 -*-
|
||
"""
|
||
Simplified configuration loader for dispatcher.
|
||
统一使用 config.yaml,向后兼容旧的 JSON 格式。
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
from typing import Any, Dict
|
||
|
||
try:
|
||
import yaml
|
||
YAML_AVAILABLE = True
|
||
except ImportError:
|
||
YAML_AVAILABLE = False
|
||
|
||
|
||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||
|
||
# 新配置路径
|
||
CONFIG_YAML_PATH = os.path.join(BASE_DIR, "config.yaml")
|
||
CONFIG_EXAMPLE_YAML_PATH = os.path.join(BASE_DIR, "config.example.yaml")
|
||
|
||
|
||
def load_config_file(path: str) -> Dict[str, Any]:
|
||
"""加载配置文件(支持 JSON 和 YAML)"""
|
||
if not os.path.exists(path):
|
||
return {}
|
||
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
if path.endswith(('.yaml', '.yml')):
|
||
if not YAML_AVAILABLE:
|
||
raise ImportError("PyYAML is required. Install: pip install pyyaml")
|
||
return yaml.safe_load(f) or {}
|
||
else:
|
||
return json.load(f)
|
||
|
||
|
||
def load_dispatcher_config() -> Dict[str, Any]:
|
||
"""
|
||
加载 dispatcher 配置
|
||
|
||
优先级:
|
||
1. config.yaml(新格式,推荐)
|
||
2. config/config.example.json(向后兼容)
|
||
"""
|
||
# 尝试新格式
|
||
if os.path.exists(CONFIG_YAML_PATH):
|
||
print(f"[Config] Loading from {CONFIG_YAML_PATH}")
|
||
return load_config_file(CONFIG_YAML_PATH)
|
||
|
||
# 尝试示例配置
|
||
if os.path.exists(CONFIG_EXAMPLE_YAML_PATH):
|
||
print(f"[Config] Loading from {CONFIG_EXAMPLE_YAML_PATH}")
|
||
return load_config_file(CONFIG_EXAMPLE_YAML_PATH)
|
||
|
||
# 向后兼容:尝试旧的 JSON 配置
|
||
old_config_path = os.path.join(BASE_DIR, "config", "config.example.json")
|
||
if os.path.exists(old_config_path):
|
||
print(f"[Config] Loading from {old_config_path} (legacy)")
|
||
print("[Config] Consider migrating to config.yaml")
|
||
return load_config_file(old_config_path)
|
||
|
||
raise FileNotFoundError(
|
||
"No configuration file found. Expected one of:\n"
|
||
f" - {CONFIG_YAML_PATH}\n"
|
||
f" - {CONFIG_EXAMPLE_YAML_PATH}\n"
|
||
"Create config.yaml from config.example.yaml"
|
||
)
|
||
|
||
|
||
# 测试
|
||
if __name__ == "__main__":
|
||
config = load_dispatcher_config()
|
||
print(f"\n✓ Config loaded successfully")
|
||
print(f" Instance: {config.get('INSTANCE_NAME')}")
|
||
print(f" Redis: {config.get('REDIS_HOST')}:{config.get('REDIS_PORT')}")
|
||
print(f" Minio: {config.get('MINIO_ENABLED')}")
|