-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_persistence.py
More file actions
88 lines (72 loc) · 2.67 KB
/
data_persistence.py
File metadata and controls
88 lines (72 loc) · 2.67 KB
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
# 数据持久化模块
import json
import os
import time
from key_storage import KeyStorage
class DataPersistence:
"""
数据持久化类,用于保存和加载密钥信息
"""
def __init__(self, key_storage, file_path="keys_data.json"):
"""
初始化数据持久化对象
Args:
key_storage (KeyStorage): 密钥存储对象
file_path (str): 数据文件路径
"""
self.key_storage = key_storage
self.file_path = file_path
def save_data(self):
"""
保存密钥数据到文件
Returns:
bool: 保存是否成功
"""
try:
data = {
"valid_keys": self.key_storage.get_all_valid_keys(),
"invalid_keys": self.key_storage.get_all_invalid_keys(),
"last_save": time.time()
}
with open(self.file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
return True
except Exception as e:
print(f"保存数据失败: {e}")
return False
def load_data(self):
"""
从文件加载密钥数据
Returns:
bool: 加载是否成功
"""
if not os.path.exists(self.file_path):
print(f"数据文件不存在: {self.file_path}")
return False
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 清空当前存储
self.key_storage.valid_keys.clear()
self.key_storage.invalid_keys.clear()
# 加载有效密钥
for key, info in data.get("valid_keys", {}).items():
self.key_storage.valid_keys[key] = info
# 加载无效密钥
for key, info in data.get("invalid_keys", {}).items():
self.key_storage.invalid_keys[key] = info
print(f"成功加载数据,有效密钥: {len(self.key_storage.valid_keys)}个,无效密钥: {len(self.key_storage.invalid_keys)}个")
return True
except Exception as e:
print(f"加载数据失败: {e}")
return False
def auto_save(self, interval=300):
"""
自动保存数据的方法,可以在单独的线程中运行
Args:
interval (int): 保存间隔(秒)
"""
while True:
self.save_data()
print(f"数据已自动保存,下次保存将在{interval}秒后")
time.sleep(interval)