54 lines
1.4 KiB
Python
54 lines
1.4 KiB
Python
"""配置管理模块"""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any, Dict
|
|
|
|
|
|
class ConfigManager:
|
|
"""配置管理器"""
|
|
|
|
_instance = None
|
|
_config: Dict[str, Any] = {}
|
|
|
|
def __new__(cls):
|
|
if cls._instance is None:
|
|
cls._instance = super().__new__(cls)
|
|
return cls._instance
|
|
|
|
def __init__(self):
|
|
if not self._config:
|
|
self._load_config()
|
|
|
|
def _load_config(self):
|
|
"""加载配置文件"""
|
|
config_dir = Path(__file__).parent.parent / "config"
|
|
config_file = config_dir / "database.json"
|
|
|
|
if not config_file.exists():
|
|
raise FileNotFoundError(f"配置文件不存在: {config_file}")
|
|
|
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
self._config = json.load(f)
|
|
|
|
def get(self, key: str, default: Any = None) -> Any:
|
|
"""获取配置项"""
|
|
keys = key.split(".")
|
|
value = self._config
|
|
for k in keys:
|
|
if isinstance(value, dict):
|
|
value = value.get(k)
|
|
if value is None:
|
|
return default
|
|
else:
|
|
return default
|
|
return value
|
|
|
|
def get_database_config(self) -> Dict[str, Any]:
|
|
"""获取数据库配置"""
|
|
return self._config.get("database", {})
|
|
|
|
|
|
# 全局配置实例
|
|
config = ConfigManager()
|