Files
douyi_guaji_main/gui/web_gui_pkg/request_parsing.py
T

30 lines
1.0 KiB
Python

import json
from http.server import BaseHTTPRequestHandler
def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None:
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Content-Length", str(len(data)))
handler.end_headers()
try:
handler.wfile.write(data)
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError):
# 客户端已主动断开时不应把正常断链打成服务端 traceback。
return None
def read_json(handler: BaseHTTPRequestHandler) -> dict:
try:
n = int(handler.headers.get("Content-Length") or 0)
except Exception:
n = 0
raw = handler.rfile.read(n) if n > 0 else b"{}"
try:
value = json.loads(raw.decode("utf-8"))
except Exception:
return {}
return value if isinstance(value, dict) else {}