Files
geo_tools/app/utils/config.py
missum db51d41aef refactor: 重构项目结构,将geo_tools重命名为app并更新相关引用
- 将主包名从geo_tools改为app
- 更新所有模块中的引用路径
- 迁移并更新测试用例
- 添加项目规则文档
- 保持原有功能不变,仅进行结构调整
2026-04-12 19:49:56 +08:00

86 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
geo_tools.utils.config
~~~~~~~~~~~~~~~~~~~~~~
配置加载辅助函数:读取 TOML / JSON / YAML 格式的任务配置文件。
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def load_json_config(path: str | Path) -> dict[str, Any]:
"""读取 JSON 配置文件。
Parameters
----------
path:
JSON 文件路径。
Returns
-------
dict
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"配置文件不存在:{path}")
with path.open(encoding="utf-8") as f:
return json.load(f)
def load_toml_config(path: str | Path) -> dict[str, Any]:
"""读取 TOML 配置文件Python 3.11+ 内置 tomllib低版本需 tomli
Parameters
----------
path:
TOML 文件路径。
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"配置文件不存在:{path}")
try:
import tomllib # Python 3.11+
except ImportError:
try:
import tomli as tomllib # type: ignore[no-redef]
except ImportError as exc:
raise ImportError(
"读取 TOML 文件需要 Python 3.11+ 或安装 tomlipip install tomli"
) from exc
with path.open("rb") as f:
return tomllib.load(f)
def load_yaml_config(path: str | Path) -> dict[str, Any]:
"""读取 YAML 配置文件(需安装 PyYAML"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"配置文件不存在:{path}")
try:
import yaml
except ImportError as exc:
raise ImportError("读取 YAML 文件需要安装 pyyamlpip install pyyaml") from exc
with path.open(encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def load_config(path: str | Path) -> dict[str, Any]:
"""根据文件扩展名自动选择解析器。
支持 ``.json``、``.toml``、``.yaml``、``.yml``。
"""
path = Path(path)
ext = path.suffix.lower()
loaders = {
".json": load_json_config,
".toml": load_toml_config,
".yaml": load_yaml_config,
".yml": load_yaml_config,
}
if ext not in loaders:
raise ValueError(f"不支持的配置文件格式:{ext!r},支持:{list(loaders)}")
return loaders[ext](path)