修复前端

This commit is contained in:
dekun
2026-05-22 11:29:34 +08:00
parent 371dec6999
commit 427f94e0e8
4 changed files with 246 additions and 114 deletions
+69 -10
View File
@@ -182,6 +182,46 @@ async def _fetch_agent_status(client: httpx.AsyncClient, ex: dict) -> dict:
}
def _exchange_brief(ex: dict | None) -> dict | None:
if not ex:
return None
return {
"id": ex.get("id"),
"key": ex.get("key"),
"name": ex.get("name"),
}
def _form_plain_dict(form) -> dict[str, str]:
out: dict[str, str] = {}
for k, v in form.multi_items() if hasattr(form, "multi_items") else form.items():
if hasattr(v, "read"):
continue
out[str(k)] = "" if v is None else str(v)
return out
def _parse_http_json_body(r: httpx.Response) -> dict:
text = (r.text or "").strip()
if not text:
return {"ok": False, "status": r.status_code, "text": "(empty body)"}
try:
data = r.json()
if isinstance(data, dict):
return data
return {"ok": False, "status": r.status_code, "text": text[:500]}
except Exception:
snippet = text[:500]
if snippet.lstrip().lower().startswith("<!") or "internal server error" in snippet.lower():
return {
"ok": False,
"status": r.status_code,
"messages": [f"实例返回 HTML 错误(HTTP {r.status_code}),请查看该 Flask 日志"],
"text": snippet,
}
return {"ok": False, "status": r.status_code, "messages": [snippet], "text": snippet}
async def _fetch_flask_json(
client: httpx.AsyncClient, ex: dict, path: str, method: str = "GET", data=None
) -> dict | None:
@@ -194,8 +234,11 @@ async def _fetch_flask_json(
else:
r = await client.post(f"{base}{path}", headers=_hub_headers(), data=data, timeout=120.0)
if r.status_code >= 400:
return {"ok": False, "status": r.status_code, "text": (r.text or "")[:500]}
return r.json()
parsed = _parse_http_json_body(r)
parsed.setdefault("ok", False)
parsed.setdefault("status", r.status_code)
return parsed
return _parse_http_json_body(r)
except Exception as e:
return {"ok": False, "error": str(e)}
@@ -308,10 +351,18 @@ async def api_trade_order(exchange_id: str, request: Request):
ex = _find_exchange(exchange_id)
if not ex or not ex.get("enabled"):
raise HTTPException(status_code=404, detail="账户未启用")
form = await request.form()
async with httpx.AsyncClient() as client:
result = await _fetch_flask_json(client, ex, "/api/hub/add_order", "POST", dict(form))
return {"exchange": ex, "result": result}
try:
form = _form_plain_dict(await request.form())
async with httpx.AsyncClient() as client:
result = await _fetch_flask_json(client, ex, "/api/hub/add_order", "POST", form)
return {"exchange": _exchange_brief(ex), "result": result}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
{"exchange": _exchange_brief(ex), "result": {"ok": False, "messages": [str(e)]}},
status_code=200,
)
@app.post("/api/trade/key/{exchange_id}")
@@ -321,10 +372,18 @@ async def api_trade_key(exchange_id: str, request: Request):
raise HTTPException(status_code=404, detail="账户未启用")
if "key" not in (ex.get("capabilities") or []):
raise HTTPException(status_code=400, detail="该账户不支持关键位")
form = await request.form()
async with httpx.AsyncClient() as client:
result = await _fetch_flask_json(client, ex, "/api/hub/add_key", "POST", dict(form))
return {"exchange": ex, "result": result}
try:
form = _form_plain_dict(await request.form())
async with httpx.AsyncClient() as client:
result = await _fetch_flask_json(client, ex, "/api/hub/add_key", "POST", form)
return {"exchange": _exchange_brief(ex), "result": result}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
{"exchange": _exchange_brief(ex), "result": {"ok": False, "messages": [str(e)]}},
status_code=200,
)
@app.post("/api/trade/trend/preview/{exchange_id}")
+22 -3
View File
@@ -294,15 +294,34 @@
}
}
async function parseJsonResponse(r) {
const text = await r.text();
if (!text) return {};
try {
return JSON.parse(text);
} catch (e) {
const snippet = text.slice(0, 200);
throw new Error(
`HTTP ${r.status} 响应不是 JSON${snippet}${text.length > 200 ? "…" : ""}`
);
}
}
async function submitForm(path, formEl) {
const id = document.getElementById("trade-account").value;
const fd = new FormData(formEl);
try {
const r = await fetch(path + encodeURIComponent(id), { method: "POST", body: fd });
const j = await r.json();
const j = await parseJsonResponse(r);
const res = j.result || {};
const msgs = (res.messages || []).join("\n") || JSON.stringify(res, null, 2);
showToast(msgs, !res.ok);
const msgs =
(res.messages || []).join("\n") ||
res.error ||
res.msg ||
res.text ||
JSON.stringify(res, null, 2);
const failed = res.ok === false || r.status >= 400 || !!res.error || !!res.text;
showToast(msgs || (failed ? "操作失败" : "已提交"), failed);
if (res.ok && res.preview) {
showTrendPreview(res);
}