|
"""
|
|
API路由模块 - 处理所有API端点请求
|
|
"""
|
|
from flask import Blueprint, request, jsonify
|
|
from models.api_key import ApiKeyManager
|
|
|
|
|
|
api_bp = Blueprint('api', __name__, url_prefix='/api')
|
|
|
|
@api_bp.route('/keys', methods=['GET'])
|
|
def get_api_keys():
|
|
"""获取所有API密钥"""
|
|
return jsonify(ApiKeyManager.get_all_keys())
|
|
|
|
@api_bp.route('/keys', methods=['POST'])
|
|
def add_api_key():
|
|
"""添加新的API密钥"""
|
|
data = request.json
|
|
|
|
new_key = ApiKeyManager.add_key(
|
|
platform=data.get("platform"),
|
|
name=data.get("name"),
|
|
key=data.get("key")
|
|
)
|
|
|
|
return jsonify({"success": True, "key": new_key})
|
|
|
|
@api_bp.route('/keys/<key_id>', methods=['DELETE'])
|
|
def delete_api_key(key_id):
|
|
"""删除指定的API密钥"""
|
|
success = ApiKeyManager.delete_key(key_id)
|
|
|
|
return jsonify({"success": success})
|
|
|
|
@api_bp.route('/keys/bulk-delete', methods=['POST'])
|
|
def bulk_delete_api_keys():
|
|
"""批量删除多个API密钥"""
|
|
data = request.json
|
|
key_ids = data.get("ids", [])
|
|
|
|
if not key_ids:
|
|
return jsonify({"success": False, "error": "没有提供要删除的密钥ID"}), 400
|
|
|
|
deleted_count = ApiKeyManager.bulk_delete(key_ids)
|
|
|
|
return jsonify({
|
|
"success": True,
|
|
"deleted_count": deleted_count,
|
|
"message": f"成功删除 {deleted_count} 个API密钥"
|
|
})
|
|
|
|
@api_bp.route('/keys/bulk-add', methods=['POST'])
|
|
def bulk_add_api_keys():
|
|
"""批量添加多个API密钥"""
|
|
data = request.json
|
|
keys_data = data.get("keys", [])
|
|
|
|
if not keys_data:
|
|
return jsonify({"success": False, "error": "没有提供要添加的密钥数据"}), 400
|
|
|
|
added_keys = ApiKeyManager.bulk_add_keys(keys_data)
|
|
|
|
return jsonify({
|
|
"success": True,
|
|
"added_count": len(added_keys),
|
|
"keys": added_keys,
|
|
"message": f"成功添加 {len(added_keys)} 个API密钥"
|
|
})
|
|
|
|
@api_bp.route('/keys/update/<key_id>', methods=['POST', 'GET'])
|
|
def update_api_key_status(key_id):
|
|
"""更新API密钥状态"""
|
|
from core.update import update
|
|
try:
|
|
print(f"正在更新密钥ID: {key_id}")
|
|
result = update(key_id)
|
|
print(f"更新结果: {result}")
|
|
return jsonify({"success": True, "data": result})
|
|
except Exception as e:
|
|
import traceback
|
|
error_msg = str(e)
|
|
trace = traceback.format_exc()
|
|
print(f"更新密钥时出错: {error_msg}\n{trace}")
|
|
return jsonify({"success": False, "error": error_msg, "traceback": trace}), 500
|
|
|
|
@api_bp.route('/keys/<key_id>', methods=['PUT'])
|
|
def edit_api_key(key_id):
|
|
"""更新API密钥信息"""
|
|
data = request.json
|
|
|
|
updated_key = ApiKeyManager.update_key(
|
|
key_id=key_id,
|
|
name=data.get("name"),
|
|
key=data.get("key")
|
|
)
|
|
|
|
if not updated_key:
|
|
return jsonify({"success": False, "error": "未找到指定的密钥"}), 404
|
|
|
|
return jsonify({"success": True, "key": updated_key})
|
|
|