storage.py 886 B

1234567891011121314151617181920212223242526272829
  1. import os
  2. import json
  3. class Storage:
  4. def __init__(self):
  5. self._file_path = os.path.join(os.path.dirname(__file__), "device_data.json")
  6. self._cache = None
  7. def get_device_data(self):
  8. if self._cache is not None:
  9. return self._cache
  10. if not os.path.exists(self._file_path):
  11. return {}
  12. try:
  13. with open(self._file_path, "r", encoding="utf-8") as f:
  14. self._cache = json.load(f)
  15. return self._cache
  16. except Exception:
  17. return {}
  18. def set_device_data(self, data):
  19. if not isinstance(data, dict):
  20. raise ValueError("data must be a dict")
  21. self._cache = data
  22. try:
  23. with open(self._file_path, "w", encoding="utf-8") as f:
  24. json.dump(data, f, ensure_ascii=False)
  25. except Exception:
  26. pass