rewrited logic structure

This commit is contained in:
2026-09-09 16:43:57 +08:00
parent 1947a27514
commit ac6d2cf3b4
20 changed files with 1717 additions and 1496 deletions

View File

@@ -0,0 +1,41 @@
"""HTTP 响应和 Cookie 工具。"""
from __future__ import annotations
import json
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler
from typing import Any
from group_system.config import SESSION_DAYS
def json_response(
status: int | HTTPStatus,
payload: Any,
cookies: list[dict[str, Any]] | None = None,
):
"""Return a callable that serializes and sends a JSON response."""
def send(handler: BaseHTTPRequestHandler):
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
handler.send_response(int(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(body)))
for cookie in cookies or []:
handler.send_header("Set-Cookie", cookie["value"])
handler.end_headers()
handler.wfile.write(body)
return send
def make_session_cookie(token: str) -> str:
return (
f"GROUP_SESSION={token}; Path=/; HttpOnly; SameSite=Lax; "
f"Max-Age={SESSION_DAYS * 86400}"
)
def clear_session_cookie() -> str:
return "GROUP_SESSION=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"