|
|
@@ -0,0 +1,52 @@
|
|
|
+"""
|
|
|
+配置提供者实现(基于本地 YAML 文件)
|
|
|
+
|
|
|
+该模块实现了 file_parse.interfaces.ConfigProvider 接口,
|
|
|
+统一从当前包下的 config.yaml 读取配置。
|
|
|
+"""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+from pathlib import Path
|
|
|
+from typing import Any, Dict
|
|
|
+
|
|
|
+import yaml
|
|
|
+
|
|
|
+
|
|
|
+from ..interfaces import ConfigProvider
|
|
|
+
|
|
|
+
|
|
|
+class YamlConfigProvider(ConfigProvider):
|
|
|
+ """简单的 YAML 配置实现。"""
|
|
|
+
|
|
|
+ def __init__(self, config_path: Path | None = None) -> None:
|
|
|
+ if config_path is None:
|
|
|
+ config_path = Path(__file__).parent / "config.yaml"
|
|
|
+ self._path = Path(config_path)
|
|
|
+ self._data: Dict[str, Any] = {}
|
|
|
+ self._load()
|
|
|
+
|
|
|
+ def _load(self) -> None:
|
|
|
+ if not self._path.exists():
|
|
|
+ raise FileNotFoundError(f"配置文件不存在: {self._path}")
|
|
|
+ with self._path.open("r", encoding="utf-8") as f:
|
|
|
+ self._data = yaml.safe_load(f) or {}
|
|
|
+
|
|
|
+ def get(self, key_path: str, default: Any = None) -> Any:
|
|
|
+ keys = key_path.split(".")
|
|
|
+ cur: Any = self._data
|
|
|
+ for k in keys:
|
|
|
+ if isinstance(cur, dict) and k in cur:
|
|
|
+ cur = cur[k]
|
|
|
+ else:
|
|
|
+ return default
|
|
|
+ return cur
|
|
|
+
|
|
|
+
|
|
|
+# 默认全局配置提供者,可在需要时直接导入使用
|
|
|
+default_config_provider = YamlConfigProvider()
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|