Update models/api_key.py
Browse files- models/api_key.py +336 -345
models/api_key.py
CHANGED
|
@@ -1,345 +1,336 @@
|
|
| 1 |
-
"""
|
| 2 |
-
API密钥模型 - 处理API密钥的CRUD操作
|
| 3 |
-
"""
|
| 4 |
-
import json
|
| 5 |
-
import uuid
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
import os
|
| 8 |
-
import pytz
|
| 9 |
-
import sqlite3
|
| 10 |
-
from utils.db import get_db_connection
|
| 11 |
-
from config import API_KEYS_FILE, DATABASE_PATH
|
| 12 |
-
|
| 13 |
-
class ApiKeyManager:
|
| 14 |
-
"""管理API密钥的类"""
|
| 15 |
-
|
| 16 |
-
@staticmethod
|
| 17 |
-
def load_keys():
|
| 18 |
-
"""加载所有API密钥 (兼容旧的JSON方式)"""
|
| 19 |
-
if not os.path.exists(API_KEYS_FILE):
|
| 20 |
-
with open(API_KEYS_FILE, 'w', encoding='utf-8') as f:
|
| 21 |
-
json.dump({"api_keys": []}, f, ensure_ascii=False, indent=2)
|
| 22 |
-
return {"api_keys": []}
|
| 23 |
-
|
| 24 |
-
try:
|
| 25 |
-
with open(API_KEYS_FILE, 'r', encoding='utf-8') as f:
|
| 26 |
-
return json.load(f)
|
| 27 |
-
except json.JSONDecodeError:
|
| 28 |
-
return {"api_keys": []}
|
| 29 |
-
|
| 30 |
-
@staticmethod
|
| 31 |
-
def save_keys(data):
|
| 32 |
-
"""保存API密钥数据 (兼容旧的JSON方式)"""
|
| 33 |
-
with open(API_KEYS_FILE, 'w', encoding='utf-8') as f:
|
| 34 |
-
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 35 |
-
|
| 36 |
-
@staticmethod
|
| 37 |
-
def get_all_keys():
|
| 38 |
-
"""获取所有密钥"""
|
| 39 |
-
conn = get_db_connection()
|
| 40 |
-
try:
|
| 41 |
-
cursor = conn.cursor()
|
| 42 |
-
cursor.execute('SELECT * FROM api_keys')
|
| 43 |
-
rows = cursor.fetchall()
|
| 44 |
-
|
| 45 |
-
# 转换为字典列表
|
| 46 |
-
api_keys = []
|
| 47 |
-
for row in rows:
|
| 48 |
-
key_dict = dict(row)
|
| 49 |
-
# 转换success字段从整数为布尔值
|
| 50 |
-
key_dict['success'] = bool(key_dict['success'])
|
| 51 |
-
api_keys.append(key_dict)
|
| 52 |
-
|
| 53 |
-
return {"api_keys": api_keys}
|
| 54 |
-
except sqlite3.Error as e:
|
| 55 |
-
print(f"获取所有密钥时出错: {str(e)}")
|
| 56 |
-
# 如果数据库出错,尝试从JSON文件加载
|
| 57 |
-
return ApiKeyManager.load_keys()
|
| 58 |
-
finally:
|
| 59 |
-
conn.close()
|
| 60 |
-
|
| 61 |
-
@staticmethod
|
| 62 |
-
def add_key(platform, name, key):
|
| 63 |
-
"""添加新的API密钥"""
|
| 64 |
-
# 过滤掉key中的单引号、双引号、小括号、方括号和空格,防止存储时出错
|
| 65 |
-
if key:
|
| 66 |
-
key = key.replace("'", "").replace('"', "").replace('(', "").replace(')', "").replace('[', "").replace(']', "").replace(' ', "")
|
| 67 |
-
|
| 68 |
-
current_time = datetime.now(pytz.timezone('Asia/Shanghai')).isoformat()
|
| 69 |
-
new_key_id = str(uuid.uuid4())
|
| 70 |
-
|
| 71 |
-
new_key = {
|
| 72 |
-
"id": new_key_id,
|
| 73 |
-
"platform": platform,
|
| 74 |
-
"name": name,
|
| 75 |
-
"key": key,
|
| 76 |
-
"created_at": current_time,
|
| 77 |
-
"updated_at": current_time,
|
| 78 |
-
"success": False,
|
| 79 |
-
"return_message": "等待测试",
|
| 80 |
-
"states": "",
|
| 81 |
-
"balance": 0
|
| 82 |
-
}
|
| 83 |
-
|
| 84 |
-
conn = get_db_connection()
|
| 85 |
-
try:
|
| 86 |
-
cursor = conn.cursor()
|
| 87 |
-
cursor.execute('''
|
| 88 |
-
INSERT INTO api_keys
|
| 89 |
-
(id, platform, name, key, created_at, updated_at, success, return_message, states, balance)
|
| 90 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 91 |
-
''', (
|
| 92 |
-
new_key_id,
|
| 93 |
-
platform,
|
| 94 |
-
name,
|
| 95 |
-
key,
|
| 96 |
-
current_time,
|
| 97 |
-
current_time,
|
| 98 |
-
0, # success是整数: 0表示False
|
| 99 |
-
"等待测试",
|
| 100 |
-
"",
|
| 101 |
-
0
|
| 102 |
-
))
|
| 103 |
-
conn.commit()
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
cursor.
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
#
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
"
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
added_keys
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
return added_keys
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
cursor
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
updated_key = k
|
| 338 |
-
break
|
| 339 |
-
|
| 340 |
-
if updated_key:
|
| 341 |
-
ApiKeyManager.save_keys(api_keys_data)
|
| 342 |
-
|
| 343 |
-
return updated_key
|
| 344 |
-
finally:
|
| 345 |
-
conn.close()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
API密钥模型 - 处理API密钥的CRUD操作
|
| 3 |
+
"""
|
| 4 |
+
import json
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import os
|
| 8 |
+
import pytz
|
| 9 |
+
import sqlite3
|
| 10 |
+
from utils.db import get_db_connection
|
| 11 |
+
from config import API_KEYS_FILE, DATABASE_PATH
|
| 12 |
+
|
| 13 |
+
class ApiKeyManager:
|
| 14 |
+
"""管理API密钥的类"""
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
def load_keys():
|
| 18 |
+
"""加载所有API密钥 (兼容旧的JSON方式)"""
|
| 19 |
+
if not os.path.exists(API_KEYS_FILE):
|
| 20 |
+
with open(API_KEYS_FILE, 'w', encoding='utf-8') as f:
|
| 21 |
+
json.dump({"api_keys": []}, f, ensure_ascii=False, indent=2)
|
| 22 |
+
return {"api_keys": []}
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
with open(API_KEYS_FILE, 'r', encoding='utf-8') as f:
|
| 26 |
+
return json.load(f)
|
| 27 |
+
except json.JSONDecodeError:
|
| 28 |
+
return {"api_keys": []}
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def save_keys(data):
|
| 32 |
+
"""保存API密钥数据 (兼容旧的JSON方式)"""
|
| 33 |
+
with open(API_KEYS_FILE, 'w', encoding='utf-8') as f:
|
| 34 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def get_all_keys():
|
| 38 |
+
"""获取所有密钥"""
|
| 39 |
+
conn = get_db_connection()
|
| 40 |
+
try:
|
| 41 |
+
cursor = conn.cursor()
|
| 42 |
+
cursor.execute('SELECT * FROM api_keys')
|
| 43 |
+
rows = cursor.fetchall()
|
| 44 |
+
|
| 45 |
+
# 转换为字典列表
|
| 46 |
+
api_keys = []
|
| 47 |
+
for row in rows:
|
| 48 |
+
key_dict = dict(row)
|
| 49 |
+
# 转换success字段从整数为布尔值
|
| 50 |
+
key_dict['success'] = bool(key_dict['success'])
|
| 51 |
+
api_keys.append(key_dict)
|
| 52 |
+
|
| 53 |
+
return {"api_keys": api_keys}
|
| 54 |
+
except sqlite3.Error as e:
|
| 55 |
+
print(f"获取所有密钥时出错: {str(e)}")
|
| 56 |
+
# 如果数据库出错,尝试从JSON文件加载
|
| 57 |
+
return ApiKeyManager.load_keys()
|
| 58 |
+
finally:
|
| 59 |
+
conn.close()
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def add_key(platform, name, key):
|
| 63 |
+
"""添加新的API密钥"""
|
| 64 |
+
# 过滤掉key中的单引号、双引号、小括号、方括号和空格,防止存储时出错
|
| 65 |
+
if key:
|
| 66 |
+
key = key.replace("'", "").replace('"', "").replace('(', "").replace(')', "").replace('[', "").replace(']', "").replace(' ', "")
|
| 67 |
+
|
| 68 |
+
current_time = datetime.now(pytz.timezone('Asia/Shanghai')).isoformat()
|
| 69 |
+
new_key_id = str(uuid.uuid4())
|
| 70 |
+
|
| 71 |
+
new_key = {
|
| 72 |
+
"id": new_key_id,
|
| 73 |
+
"platform": platform,
|
| 74 |
+
"name": name,
|
| 75 |
+
"key": key,
|
| 76 |
+
"created_at": current_time,
|
| 77 |
+
"updated_at": current_time,
|
| 78 |
+
"success": False,
|
| 79 |
+
"return_message": "等待测试",
|
| 80 |
+
"states": "",
|
| 81 |
+
"balance": 0
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
conn = get_db_connection()
|
| 85 |
+
try:
|
| 86 |
+
cursor = conn.cursor()
|
| 87 |
+
cursor.execute('''
|
| 88 |
+
INSERT INTO api_keys
|
| 89 |
+
(id, platform, name, key, created_at, updated_at, success, return_message, states, balance)
|
| 90 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 91 |
+
''', (
|
| 92 |
+
new_key_id,
|
| 93 |
+
platform,
|
| 94 |
+
name,
|
| 95 |
+
key,
|
| 96 |
+
current_time,
|
| 97 |
+
current_time,
|
| 98 |
+
0, # success是整数: 0表示False
|
| 99 |
+
"等待测试",
|
| 100 |
+
"",
|
| 101 |
+
0
|
| 102 |
+
))
|
| 103 |
+
conn.commit()
|
| 104 |
+
|
| 105 |
+
return new_key
|
| 106 |
+
except sqlite3.Error as e:
|
| 107 |
+
print(f"添加密钥时出错: {str(e)}")
|
| 108 |
+
conn.rollback()
|
| 109 |
+
# 如果数据库出错,尝试使用JSON方式保存
|
| 110 |
+
api_keys_data = ApiKeyManager.load_keys()
|
| 111 |
+
api_keys_data["api_keys"].append(new_key)
|
| 112 |
+
ApiKeyManager.save_keys(api_keys_data)
|
| 113 |
+
return new_key
|
| 114 |
+
finally:
|
| 115 |
+
conn.close()
|
| 116 |
+
|
| 117 |
+
@staticmethod
|
| 118 |
+
def delete_key(key_id):
|
| 119 |
+
"""删除指定的API密钥"""
|
| 120 |
+
conn = get_db_connection()
|
| 121 |
+
try:
|
| 122 |
+
cursor = conn.cursor()
|
| 123 |
+
cursor.execute('DELETE FROM api_keys WHERE id = ?', (key_id,))
|
| 124 |
+
deleted = cursor.rowcount > 0
|
| 125 |
+
conn.commit()
|
| 126 |
+
return deleted
|
| 127 |
+
except sqlite3.Error as e:
|
| 128 |
+
print(f"删除密钥时出错: {str(e)}")
|
| 129 |
+
conn.rollback()
|
| 130 |
+
# 如果数据库出错,尝试从JSON文件删除
|
| 131 |
+
api_keys_data = ApiKeyManager.load_keys()
|
| 132 |
+
original_count = len(api_keys_data["api_keys"])
|
| 133 |
+
api_keys_data["api_keys"] = [k for k in api_keys_data["api_keys"] if k.get("id") != key_id]
|
| 134 |
+
|
| 135 |
+
if len(api_keys_data["api_keys"]) < original_count:
|
| 136 |
+
ApiKeyManager.save_keys(api_keys_data)
|
| 137 |
+
return True
|
| 138 |
+
return False
|
| 139 |
+
finally:
|
| 140 |
+
conn.close()
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
def bulk_delete(key_ids):
|
| 144 |
+
"""批量删除多个API密钥"""
|
| 145 |
+
if not key_ids:
|
| 146 |
+
return 0
|
| 147 |
+
|
| 148 |
+
conn = get_db_connection()
|
| 149 |
+
try:
|
| 150 |
+
cursor = conn.cursor()
|
| 151 |
+
# 获取当前的密钥数量
|
| 152 |
+
cursor.execute('SELECT COUNT(*) FROM api_keys')
|
| 153 |
+
original_count = cursor.fetchone()[0]
|
| 154 |
+
|
| 155 |
+
# 使用参数化查询构建占位符
|
| 156 |
+
placeholders = ','.join(['?'] * len(key_ids))
|
| 157 |
+
cursor.execute(f'DELETE FROM api_keys WHERE id IN ({placeholders})', key_ids)
|
| 158 |
+
|
| 159 |
+
# 获取删除后的密钥数量
|
| 160 |
+
cursor.execute('SELECT COUNT(*) FROM api_keys')
|
| 161 |
+
new_count = cursor.fetchone()[0]
|
| 162 |
+
|
| 163 |
+
conn.commit()
|
| 164 |
+
return original_count - new_count
|
| 165 |
+
except sqlite3.Error as e:
|
| 166 |
+
print(f"批量删除密钥时出错: {str(e)}")
|
| 167 |
+
conn.rollback()
|
| 168 |
+
# 如果数据库出错,尝试从JSON文件删除
|
| 169 |
+
api_keys_data = ApiKeyManager.load_keys()
|
| 170 |
+
original_count = len(api_keys_data["api_keys"])
|
| 171 |
+
api_keys_data["api_keys"] = [k for k in api_keys_data["api_keys"] if k.get("id") not in key_ids]
|
| 172 |
+
|
| 173 |
+
deleted_count = original_count - len(api_keys_data["api_keys"])
|
| 174 |
+
if deleted_count > 0:
|
| 175 |
+
ApiKeyManager.save_keys(api_keys_data)
|
| 176 |
+
|
| 177 |
+
return deleted_count
|
| 178 |
+
finally:
|
| 179 |
+
conn.close()
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def bulk_add_keys(keys_data):
|
| 183 |
+
"""批量添加多个API密钥
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
keys_data: 包含多个密钥信息的列表,每个元素包含platform、name、key
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
添加的密钥列表
|
| 190 |
+
"""
|
| 191 |
+
if not keys_data:
|
| 192 |
+
return []
|
| 193 |
+
|
| 194 |
+
added_keys = []
|
| 195 |
+
now = datetime.now(pytz.timezone('Asia/Shanghai')).isoformat()
|
| 196 |
+
|
| 197 |
+
conn = get_db_connection()
|
| 198 |
+
try:
|
| 199 |
+
cursor = conn.cursor()
|
| 200 |
+
|
| 201 |
+
for key_info in keys_data:
|
| 202 |
+
platform = key_info.get("platform")
|
| 203 |
+
name = key_info.get("name")
|
| 204 |
+
key = key_info.get("key")
|
| 205 |
+
|
| 206 |
+
# 过滤掉key中的单引号、双引号、小括号、方括号和空格,防止存储时出错
|
| 207 |
+
if key:
|
| 208 |
+
key = key.replace("'", "").replace('"', "").replace('(', "").replace(')', "").replace('[', "").replace(']', "").replace(' ', "")
|
| 209 |
+
|
| 210 |
+
new_key_id = str(uuid.uuid4())
|
| 211 |
+
|
| 212 |
+
new_key = {
|
| 213 |
+
"id": new_key_id,
|
| 214 |
+
"platform": platform,
|
| 215 |
+
"name": name,
|
| 216 |
+
"key": key,
|
| 217 |
+
"created_at": now,
|
| 218 |
+
"updated_at": now,
|
| 219 |
+
"success": False,
|
| 220 |
+
"return_message": "等待测试",
|
| 221 |
+
"states": "",
|
| 222 |
+
"balance": 0
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
cursor.execute('''
|
| 226 |
+
INSERT INTO api_keys
|
| 227 |
+
(id, platform, name, key, created_at, updated_at, success, return_message, states, balance)
|
| 228 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 229 |
+
''', (
|
| 230 |
+
new_key_id,
|
| 231 |
+
platform,
|
| 232 |
+
name,
|
| 233 |
+
key,
|
| 234 |
+
now,
|
| 235 |
+
now,
|
| 236 |
+
0, # success是整数: 0表示False
|
| 237 |
+
"等待测试",
|
| 238 |
+
"",
|
| 239 |
+
0
|
| 240 |
+
))
|
| 241 |
+
|
| 242 |
+
added_keys.append(new_key)
|
| 243 |
+
|
| 244 |
+
conn.commit()
|
| 245 |
+
|
| 246 |
+
# 在批量添加完成后,启动一个单独的线程来验证所有新添加的密钥
|
| 247 |
+
from core.update import update
|
| 248 |
+
from threading import Thread
|
| 249 |
+
|
| 250 |
+
def validate_keys():
|
| 251 |
+
for new_key in added_keys:
|
| 252 |
+
try:
|
| 253 |
+
key_id = new_key["id"]
|
| 254 |
+
print(f"[自动验证] 正在验证密钥 ID: {key_id}")
|
| 255 |
+
update_result = update(key_id)
|
| 256 |
+
print(f"[自动验证] 密钥验证结果: {update_result}")
|
| 257 |
+
except Exception as e:
|
| 258 |
+
print(f"[自动验证] 验证密钥时出错: {str(e)}")
|
| 259 |
+
|
| 260 |
+
# 启动验证线程
|
| 261 |
+
print(f"[自动验证] 启动验证线程,验证 {len(added_keys)} 个新添加的密钥")
|
| 262 |
+
validation_thread = Thread(target=validate_keys)
|
| 263 |
+
validation_thread.daemon = True # 设置为守护线程,当主线程退出时自动结束
|
| 264 |
+
validation_thread.start()
|
| 265 |
+
|
| 266 |
+
return added_keys
|
| 267 |
+
except sqlite3.Error as e:
|
| 268 |
+
print(f"批量添加密钥时出错: {str(e)}")
|
| 269 |
+
conn.rollback()
|
| 270 |
+
# 如果数据库出错,尝试使用JSON方式保存
|
| 271 |
+
api_keys_data = ApiKeyManager.load_keys()
|
| 272 |
+
for key in added_keys:
|
| 273 |
+
api_keys_data["api_keys"].append(key)
|
| 274 |
+
ApiKeyManager.save_keys(api_keys_data)
|
| 275 |
+
return added_keys
|
| 276 |
+
finally:
|
| 277 |
+
conn.close()
|
| 278 |
+
|
| 279 |
+
@staticmethod
|
| 280 |
+
def update_key(key_id, name, key):
|
| 281 |
+
"""更新API密钥信息"""
|
| 282 |
+
# 过滤掉key中的单引号、双引号、小括号、方括号和空格,防止存储时出错
|
| 283 |
+
if key:
|
| 284 |
+
key = key.replace("'", "").replace('"', "").replace('(', "").replace(')', "").replace('[', "").replace(']', "").replace(' ', "")
|
| 285 |
+
|
| 286 |
+
updated_at = datetime.now(pytz.timezone('Asia/Shanghai')).isoformat()
|
| 287 |
+
|
| 288 |
+
conn = get_db_connection()
|
| 289 |
+
try:
|
| 290 |
+
cursor = conn.cursor()
|
| 291 |
+
|
| 292 |
+
# 更新密钥
|
| 293 |
+
cursor.execute('''
|
| 294 |
+
UPDATE api_keys
|
| 295 |
+
SET name = ?, key = ?, updated_at = ?, success = ?, return_message = ?
|
| 296 |
+
WHERE id = ?
|
| 297 |
+
''', (name, key, updated_at, 0, "等待测试", key_id))
|
| 298 |
+
|
| 299 |
+
if cursor.rowcount > 0:
|
| 300 |
+
conn.commit()
|
| 301 |
+
|
| 302 |
+
# 获取更新后的密钥信息
|
| 303 |
+
cursor.execute('SELECT * FROM api_keys WHERE id = ?', (key_id,))
|
| 304 |
+
row = cursor.fetchone()
|
| 305 |
+
|
| 306 |
+
if row:
|
| 307 |
+
updated_key = dict(row)
|
| 308 |
+
# 转换success字段从整数为布尔值
|
| 309 |
+
updated_key['success'] = bool(updated_key['success'])
|
| 310 |
+
return updated_key
|
| 311 |
+
|
| 312 |
+
return None
|
| 313 |
+
except sqlite3.Error as e:
|
| 314 |
+
print(f"更新密钥时出错: {str(e)}")
|
| 315 |
+
conn.rollback()
|
| 316 |
+
|
| 317 |
+
# 如果数据库出错,尝试使用JSON方式更新
|
| 318 |
+
api_keys_data = ApiKeyManager.load_keys()
|
| 319 |
+
updated_key = None
|
| 320 |
+
for k in api_keys_data["api_keys"]:
|
| 321 |
+
if k.get("id") == key_id:
|
| 322 |
+
k["name"] = name
|
| 323 |
+
k["key"] = key
|
| 324 |
+
k["updated_at"] = updated_at
|
| 325 |
+
# 重置验证状态
|
| 326 |
+
k["success"] = False
|
| 327 |
+
k["return_message"] = "等待测试"
|
| 328 |
+
updated_key = k
|
| 329 |
+
break
|
| 330 |
+
|
| 331 |
+
if updated_key:
|
| 332 |
+
ApiKeyManager.save_keys(api_keys_data)
|
| 333 |
+
|
| 334 |
+
return updated_key
|
| 335 |
+
finally:
|
| 336 |
+
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|