Files
chongming_template_fastapi/{{ cookiecutter.project_name }}/public/utils/config.py
T

89 lines
2.4 KiB
Python
Raw Normal View History

2026-01-31 16:00:12 +08:00
# config_loader.py - 读取config.toml的示例代码
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
import os
2026-03-06 14:56:44 +08:00
import sys
2026-01-31 16:00:12 +08:00
from pathlib import Path
from typing import Any, Dict, Optional
2026-03-06 14:56:44 +08:00
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
2026-01-31 16:00:12 +08:00
class ConfigLoader:
"""TOML配置文件加载器"""
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def __init__(self, config_path: Optional[str] = None):
"""
初始化配置加载器
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
Args:
config_path: 配置文件路径,如果为None则自动查找
"""
if config_path is None:
# 自动查找配置文件
config_path = self._find_config_file()
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
self.config_path = Path(config_path)
self._config: Dict[str, Any] = {}
self.load()
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def _find_config_file(self) -> str:
"""自动查找配置文件"""
possible_paths = [
"config.toml",
"config/config.toml",
"~/.config/myapp/config.toml",
2026-03-06 14:56:44 +08:00
"/etc/myapp/config.toml",
2026-01-31 16:00:12 +08:00
]
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
for path in possible_paths:
expanded_path = os.path.expanduser(path)
if os.path.exists(expanded_path):
return expanded_path
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
raise FileNotFoundError("未找到配置文件")
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def load(self) -> None:
"""加载配置文件"""
if not self.config_path.exists():
raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
2026-03-06 14:56:44 +08:00
with open(self.config_path, "r", encoding="utf-8") as f:
self._config = tomllib.loads(f.read())
2026-01-31 16:00:12 +08:00
def get(self, key: str, default: Any = None) -> Any:
"""获取配置值,支持点号分隔的路径"""
2026-03-06 14:56:44 +08:00
keys = key.split(".")
2026-01-31 16:00:12 +08:00
value = self._config
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
try:
for k in keys:
value = value[k]
return value
except (KeyError, TypeError):
return default
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def get_section(self, section: str) -> Dict[str, Any]:
"""获取整个配置节"""
return self._config.get(section, {})
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def reload(self) -> None:
"""重新加载配置文件"""
self.load()
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def __getitem__(self, key: str) -> Any:
"""支持字典式访问"""
return self.get(key)
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
def __contains__(self, key: str) -> bool:
"""检查配置是否存在"""
return self.get(key) is not None
2026-03-06 14:56:44 +08:00
2026-01-31 16:00:12 +08:00
@property
def all(self) -> Dict[str, Any]:
"""获取所有配置"""
return self._config