Files
HeXi/plugin_template/nonebot_plugin_template/repository.py
T

38 lines
946 B
Python
Raw Normal View History

"""Model 层的数据访问:唯一读写入口(此处用 JSON 文件示例)。"""
from __future__ import annotations
import json
import os
from pathlib import Path
# Runtime data belongs under hexi/data, not beside importable plugin code.
_DATA_DIR = Path(__file__).resolve().parents[2] / "data" / "nonebot_plugin_template"
_STORE = _DATA_DIR / "store.json"
def _load() -> dict:
if _STORE.exists():
try:
return json.loads(_STORE.read_text("utf-8"))
except json.JSONDecodeError:
return {}
return {}
def _save(data: dict) -> None:
_DATA_DIR.mkdir(parents=True, exist_ok=True)
tmp = _STORE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), "utf-8")
os.replace(tmp, _STORE) # 原子写
def get_record(key: str):
return _load().get(key)
def save_record(key: str, value) -> None:
data = _load()
data[key] = value
_save(data)