Spaces:
Running
on
Zero
Running
on
Zero
File size: 3,408 Bytes
505d2dd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
from datetime import datetime
import json
import os
import pytz
import traceback
class UserHistoryManager:
def __init__(self):
"""初始化歷史紀錄管理器"""
self.history_file = "user_history.json"
print(f"Initializing UserHistoryManager with file: {os.path.abspath(self.history_file)}")
self._init_file()
def _init_file(self):
"""初始化JSON檔案"""
try:
if not os.path.exists(self.history_file):
print(f"Creating new history file: {self.history_file}")
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump([], f)
else:
print(f"History file exists: {self.history_file}")
# 驗證檔案內容
with open(self.history_file, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Current history entries: {len(data)}")
except Exception as e:
print(f"Error in _init_file: {str(e)}")
print(traceback.format_exc())
def save_history(self, user_preferences: dict, results: list) -> bool:
"""儲存搜尋歷史,使用台北時間"""
try:
print("\nSaving history:")
print("Results to save:", results)
# 使用 pytz 創建台北時區
taipei_tz = pytz.timezone('Asia/Taipei')
# 獲取當前時間並轉換為台北時間
taipei_time = datetime.now(taipei_tz)
history_entry = {
"timestamp": taipei_time.strftime("%Y-%m-%d %H:%M:%S"),
"preferences": user_preferences,
"results": results
}
with open(self.history_file, 'r', encoding='utf-8') as f:
history = json.load(f)
# 添加新紀錄
history.append(history_entry)
# 限制保存最近的20筆記錄
if len(history) > 20:
history = history[-20:]
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump(history, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
print(f"Error saving history: {str(e)}")
return False
def get_history(self) -> list:
"""獲取搜尋歷史"""
try:
print("Attempting to read history") # Debug
with open(self.history_file, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Read {len(data)} history entries") # Debug
return data if isinstance(data, list) else []
except Exception as e:
print(f"Error reading history: {str(e)}")
print(traceback.format_exc())
return []
def clear_all_history(self) -> bool:
"""清除所有歷史紀錄"""
try:
print("Attempting to clear all history") # Debug
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump([], f)
print("History cleared successfully") # Debug
return True
except Exception as e:
print(f"Error clearing history: {str(e)}")
print(traceback.format_exc())
return False
|