47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
"""配置加载与保存:config.json 是唯一配置来源。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import threading
|
|
from dataclasses import dataclass, asdict
|
|
from pathlib import Path
|
|
|
|
CONFIG_PATH = Path(__file__).resolve().parent.parent / "config.json"
|
|
|
|
_lock = threading.Lock()
|
|
|
|
|
|
@dataclass
|
|
class Config:
|
|
"""全局配置(运行时可改的字段会在界面设置页暴露)。"""
|
|
|
|
port: int = 8000
|
|
password: str = "admin123"
|
|
global_interval_seconds: int = 300
|
|
retry_count: int = 2
|
|
timeout_seconds: int = 10
|
|
max_workers: int = 8
|
|
telegram_bot_token: str = ""
|
|
telegram_chat_id: str = ""
|
|
|
|
|
|
def load_config() -> Config:
|
|
with _lock:
|
|
if not CONFIG_PATH.exists():
|
|
cfg = Config()
|
|
save_config(cfg)
|
|
return cfg
|
|
raw = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
|
known = {f: getattr(Config, f) for f in Config.__dataclass_fields__}
|
|
data = {k: v for k, v in raw.items() if k in known}
|
|
return Config(**data)
|
|
|
|
|
|
def save_config(cfg: Config) -> None:
|
|
with _lock:
|
|
CONFIG_PATH.write_text(
|
|
json.dumps(asdict(cfg), ensure_ascii=False, indent=2),
|
|
encoding="utf-8",
|
|
)
|