""" API密钥模型 - 处理API密钥的CRUD操作 """ import json import uuid from datetime import datetime import os from config import API_KEYS_FILE class ApiKeyManager: """管理API密钥的类""" @staticmethod def load_keys(): """加载所有API密钥""" if not os.path.exists(API_KEYS_FILE): with open(API_KEYS_FILE, 'w', encoding='utf-8') as f: json.dump({"api_keys": []}, f, ensure_ascii=False, indent=2) return {"api_keys": []} try: with open(API_KEYS_FILE, 'r', encoding='utf-8') as f: return json.load(f) except json.JSONDecodeError: return {"api_keys": []} @staticmethod def save_keys(data): """保存API密钥数据""" with open(API_KEYS_FILE, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) @staticmethod def get_all_keys(): """获取所有密钥""" return ApiKeyManager.load_keys() @staticmethod def add_key(platform, name, key): """添加新的API密钥""" api_keys_data = ApiKeyManager.load_keys() # 过滤掉key中的单引号,防止存储时出错 if key and "'" in key: key = key.replace("'", "") new_key = { "id": str(uuid.uuid4()), "platform": platform, "name": name, "key": key, "created_at": datetime.now().isoformat() } api_keys_data["api_keys"].append(new_key) ApiKeyManager.save_keys(api_keys_data) return new_key @staticmethod def delete_key(key_id): """删除指定的API密钥""" api_keys_data = ApiKeyManager.load_keys() original_count = len(api_keys_data["api_keys"]) api_keys_data["api_keys"] = [k for k in api_keys_data["api_keys"] if k.get("id") != key_id] if len(api_keys_data["api_keys"]) < original_count: ApiKeyManager.save_keys(api_keys_data) return True return False @staticmethod def bulk_delete(key_ids): """批量删除多个API密钥""" if not key_ids: return 0 api_keys_data = ApiKeyManager.load_keys() original_count = len(api_keys_data["api_keys"]) api_keys_data["api_keys"] = [k for k in api_keys_data["api_keys"] if k.get("id") not in key_ids] deleted_count = original_count - len(api_keys_data["api_keys"]) if deleted_count > 0: ApiKeyManager.save_keys(api_keys_data) return deleted_count @staticmethod def update_key(key_id, name, key): """更新API密钥信息""" api_keys_data = ApiKeyManager.load_keys() # 过滤掉key中的单引号,防止存储时出错 if key and "'" in key: key = key.replace("'", "") updated_key = None for k in api_keys_data["api_keys"]: if k.get("id") == key_id: k["name"] = name k["key"] = key updated_key = k break if updated_key: ApiKeyManager.save_keys(api_keys_data) return updated_key