storage.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. 数据持久化模块,负责Todo数据的保存和加载
  3. """
  4. import json
  5. import os
  6. from typing import Dict
  7. from .todo import Todo
  8. class Storage:
  9. """数据存储类"""
  10. def __init__(self, filepath: str = "todos.json"):
  11. self.filepath = filepath
  12. def save(self, todo: Todo) -> bool:
  13. """保存Todo数据到文件"""
  14. try:
  15. data = todo.to_dict()
  16. with open(self.filepath, 'w', encoding='utf-8') as f:
  17. json.dump(data, f, ensure_ascii=False, indent=2)
  18. return True
  19. except Exception as e:
  20. print(f"保存失败: {e}")
  21. return False
  22. def load(self) -> Todo:
  23. """从文件加载Todo数据"""
  24. todo = Todo()
  25. if not os.path.exists(self.filepath):
  26. return todo
  27. try:
  28. with open(self.filepath, 'r', encoding='utf-8') as f:
  29. data = json.load(f)
  30. todo.from_dict(data)
  31. except json.JSONDecodeError:
  32. print(f"警告: {self.filepath} 文件格式错误,将创建新文件")
  33. except Exception as e:
  34. print(f"加载失败: {e}")
  35. return todo
  36. def exists(self) -> bool:
  37. """检查存储文件是否存在"""
  38. return os.path.exists(self.filepath)
  39. def delete(self) -> bool:
  40. """删除存储文件"""
  41. try:
  42. if self.exists():
  43. os.remove(self.filepath)
  44. return True
  45. except Exception as e:
  46. print(f"删除文件失败: {e}")
  47. return False