machine_store.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """机型配置管理 - 从JSON文件读写"""
  2. import json
  3. from pathlib import Path
  4. from typing import Dict, Any, Optional
  5. class MachineStore:
  6. def __init__(self, data_dir: Path):
  7. self.config_path = data_dir / "machine_configs.json"
  8. self.reuse_path = data_dir / "reuse_map.json"
  9. self._configs: Dict[str, Any] = {}
  10. self._reuse_map: Dict[str, Any] = {}
  11. self._load()
  12. def _load(self):
  13. if self.config_path.exists():
  14. self._configs = json.loads(self.config_path.read_text(encoding="utf-8"))
  15. if self.reuse_path.exists():
  16. self._reuse_map = json.loads(self.reuse_path.read_text(encoding="utf-8"))
  17. def _save(self):
  18. self.config_path.write_text(json.dumps(self._configs, ensure_ascii=False, indent=2), encoding="utf-8")
  19. def _save_reuse(self):
  20. self.reuse_path.write_text(json.dumps(self._reuse_map, ensure_ascii=False, indent=2), encoding="utf-8")
  21. @property
  22. def configs(self) -> Dict[str, Any]:
  23. return self._configs
  24. @property
  25. def reuse_map(self) -> Dict[str, Any]:
  26. return self._reuse_map
  27. def get(self, model: str) -> Optional[Dict[str, Any]]:
  28. return self._configs.get(model)
  29. def create(self, model: str, config: Dict[str, Any]) -> Dict[str, Any]:
  30. if model in self._configs:
  31. raise ValueError(f"机型 '{model}' 已存在")
  32. self._configs[model] = config
  33. self._save()
  34. return config
  35. def update(self, model: str, config: Dict[str, Any]) -> Dict[str, Any]:
  36. if model not in self._configs:
  37. raise ValueError(f"机型 '{model}' 不存在")
  38. self._configs[model] = config
  39. self._save()
  40. return config
  41. def delete(self, model: str):
  42. if model not in self._configs:
  43. raise ValueError(f"机型 '{model}' 不存在")
  44. del self._configs[model]
  45. # 同时清理复用映射
  46. if model in self._reuse_map:
  47. del self._reuse_map[model]
  48. self._save_reuse()
  49. self._save()
  50. def set_reuse(self, model: str, reuse: Optional[Dict[str, str]]):
  51. if reuse:
  52. self._reuse_map[model] = reuse
  53. elif model in self._reuse_map:
  54. del self._reuse_map[model]
  55. self._save_reuse()
  56. def load_machine_store(data_dir: Path) -> MachineStore:
  57. return MachineStore(data_dir)