| 29 | |
| 30 | |
| 31 | class HistoryService: |
| 32 | def __init__(self): |
| 33 | """ |
| 34 | 初始化历史记录服务 |
| 35 | |
| 36 | 创建历史记录存储目录和索引文件 |
| 37 | """ |
| 38 | # 历史记录存储目录(项目根目录/history) |
| 39 | self.history_dir = os.path.join( |
| 40 | os.path.dirname(os.path.dirname(os.path.dirname(__file__))), |
| 41 | "history" |
| 42 | ) |
| 43 | os.makedirs(self.history_dir, exist_ok=True) |
| 44 | |
| 45 | # 索引文件路径 |
| 46 | self.index_file = os.path.join(self.history_dir, "index.json") |
| 47 | self._init_index() |
| 48 | |
| 49 | def _init_index(self) -> None: |
| 50 | """ |
| 51 | 初始化索引文件 |
| 52 | |
| 53 | 如果索引文件不存在,则创建一个空索引 |
| 54 | """ |
| 55 | if not os.path.exists(self.index_file): |
| 56 | with open(self.index_file, "w", encoding="utf-8") as f: |
| 57 | json.dump({"records": []}, f, ensure_ascii=False, indent=2) |
| 58 | |
| 59 | def _load_index(self) -> Dict: |
| 60 | """ |
| 61 | 加载索引文件 |
| 62 | |
| 63 | Returns: |
| 64 | Dict: 索引数据,包含 records 列表 |
| 65 | """ |
| 66 | try: |
| 67 | with open(self.index_file, "r", encoding="utf-8") as f: |
| 68 | return json.load(f) |
| 69 | except Exception: |
| 70 | return {"records": []} |
| 71 | |
| 72 | def _save_index(self, index: Dict) -> None: |
| 73 | """ |
| 74 | 保存索引文件 |
| 75 | |
| 76 | Args: |
| 77 | index: 索引数据 |
| 78 | """ |
| 79 | with open(self.index_file, "w", encoding="utf-8") as f: |
| 80 | json.dump(index, f, ensure_ascii=False, indent=2) |
| 81 | |
| 82 | def _get_record_path(self, record_id: str) -> str: |
| 83 | """ |
| 84 | 获取历史记录文件路径 |
| 85 | |
| 86 | Args: |
| 87 | record_id: 记录 ID |
| 88 |
no outgoing calls
no test coverage detected