Files
crypto_key/app.py
T
2026-05-19 01:00:26 +08:00

85 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
多账户 API 密钥管理工具 — Flask 后端
端口: 5200 (0.0.0.0 局域网可访问) | 数据: data.json
"""
import json
import uuid
from pathlib import Path
from flask import Flask, jsonify, request, send_from_directory
app = Flask(__name__)
BASE_DIR = Path(__file__).resolve().parent
DATA_FILE = BASE_DIR / "data.json"
def load_accounts():
if not DATA_FILE.exists():
return []
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
return []
except (json.JSONDecodeError, OSError):
return []
def save_accounts(accounts):
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(accounts, f, ensure_ascii=False, indent=2)
def validate_account_payload(payload):
username = (payload.get("username") or "").strip()
api_key = (payload.get("api_key") or "").strip()
api_secret = (payload.get("api_secret") or "").strip()
if not username:
return None, "账户名称不能为空"
if not api_key:
return None, "API Key 不能为空"
if not api_secret:
return None, "API Secret 不能为空"
return {"username": username, "api_key": api_key, "api_secret": api_secret}, None
@app.route("/")
def index():
return send_from_directory(BASE_DIR, "index.html")
@app.route("/api/accounts", methods=["GET"])
def list_accounts():
return jsonify(load_accounts())
@app.route("/api/accounts", methods=["POST"])
def create_account():
body = request.get_json(silent=True) or {}
account, err = validate_account_payload(body)
if err:
return jsonify({"error": err}), 400
accounts = load_accounts()
account["id"] = str(uuid.uuid4())
accounts.append(account)
save_accounts(accounts)
return jsonify(account), 201
@app.route("/api/accounts/<account_id>", methods=["DELETE"])
def delete_account(account_id):
accounts = load_accounts()
new_accounts = [a for a in accounts if a.get("id") != account_id]
if len(new_accounts) == len(accounts):
return jsonify({"error": "账户不存在"}), 404
save_accounts(new_accounts)
return jsonify({"ok": True})
if __name__ == "__main__":
# 0.0.0.0:本机 + 局域网均可访问(如 http://192.168.1.100:5200
app.run(host="0.0.0.0", port=5200, debug=False)