""" 数据持久化模块,负责Todo数据的保存和加载 """ import json import os from typing import Dict from .todo import Todo class Storage: """数据存储类""" def __init__(self, filepath: str = "todos.json"): self.filepath = filepath def save(self, todo: Todo) -> bool: """保存Todo数据到文件""" try: data = todo.to_dict() with open(self.filepath, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) return True except Exception as e: print(f"保存失败: {e}") return False def load(self) -> Todo: """从文件加载Todo数据""" todo = Todo() if not os.path.exists(self.filepath): return todo try: with open(self.filepath, 'r', encoding='utf-8') as f: data = json.load(f) todo.from_dict(data) except json.JSONDecodeError: print(f"警告: {self.filepath} 文件格式错误,将创建新文件") except Exception as e: print(f"加载失败: {e}") return todo def exists(self) -> bool: """检查存储文件是否存在""" return os.path.exists(self.filepath) def delete(self) -> bool: """删除存储文件""" try: if self.exists(): os.remove(self.filepath) return True except Exception as e: print(f"删除文件失败: {e}") return False