Initial commit: crypto_key API key manager with PM2 and Ubuntu deploy docs
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
多账户 API 密钥管理工具 — Flask 后端
|
||||
端口: 5200 | 数据: 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__":
|
||||
app.run(host="127.0.0.1", port=5200, debug=False)
|
||||
Reference in New Issue
Block a user