Spaces:
Running
Running
Download src/core/http_utils.py from ArielJoe/Prompt-Builder: direct link, hf CLI and curl.
- Browser
- Download file 5.09 kB
-
https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/core/http_utils.py
- Command line
-
hf download hf://spaces/ArielJoe/Prompt-Builder/src/core/http_utils.py
-
curl -L -o http_utils.py https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/core/http_utils.py
5.09 kB
| """Shared stdlib HTTP server utilities for the pipeline and detector test servers.""" | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import mimetypes | |
| from collections.abc import Callable, Sequence | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| from pathlib import Path | |
| from core import config | |
| logger = logging.getLogger(__name__) | |
| _STATIC_CONTENT_TYPES: dict[str, str] = { | |
| ".html": "text/html; charset=utf-8", | |
| ".css": "text/css; charset=utf-8", | |
| ".js": "text/javascript; charset=utf-8", | |
| ".mjs": "text/javascript; charset=utf-8", | |
| ".json": "application/json; charset=utf-8", | |
| ".svg": "image/svg+xml", | |
| } | |
| def configure_logging() -> None: | |
| """Configure consistent console logging across servers.""" | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s %(levelname)-7s %(message)s", | |
| datefmt="%H:%M:%S", | |
| ) | |
| class BodyTooLargeError(ValueError): | |
| """Raised when Content-Length exceeds the configured body limit.""" | |
| class JsonRequestHandler(BaseHTTPRequestHandler): | |
| """Base HTTP handler with CORS, JSON helpers, body size cap, and safe static file serving.""" | |
| allow_cors: bool | None = None | |
| max_body_bytes: int = config.MAX_BODY_BYTES | |
| def _cors_enabled(self) -> bool: | |
| if self.allow_cors is None: | |
| return config.ENABLE_CORS | |
| return self.allow_cors | |
| def send_cors_headers(self) -> None: | |
| if not self._cors_enabled(): | |
| return | |
| self.send_header("Access-Control-Allow-Origin", "*") | |
| self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") | |
| self.send_header("Access-Control-Allow-Headers", "Content-Type") | |
| def do_OPTIONS(self) -> None: | |
| self.send_response(204) | |
| self.send_cors_headers() | |
| self.end_headers() | |
| def send_json(self, status: int, body: object) -> None: | |
| payload = json.dumps(body, ensure_ascii=False).encode("utf-8") | |
| try: | |
| self.send_response(status) | |
| self.send_header("Content-Type", "application/json; charset=utf-8") | |
| self.send_header("Content-Length", str(len(payload))) | |
| self.send_cors_headers() | |
| self.end_headers() | |
| self.wfile.write(payload) | |
| except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError): | |
| pass # Client disconnected before response finished. | |
| def read_json_body(self) -> object | None: | |
| """Read and parse JSON body; raise BodyTooLargeError if over limit, or None if invalid.""" | |
| raw_len = self.headers.get("Content-Length", "0") | |
| try: | |
| length = int(raw_len) | |
| except (TypeError, ValueError): | |
| return None | |
| if length < 0: | |
| return None | |
| if length > self.max_body_bytes: | |
| raise BodyTooLargeError(f"Request body exceeds {self.max_body_bytes} bytes") | |
| if length == 0: | |
| return {} | |
| try: | |
| return json.loads(self.rfile.read(length)) | |
| except (json.JSONDecodeError, ValueError, UnicodeDecodeError): | |
| return None | |
| def serve_static_file(self, web_dir: Path) -> None: | |
| """Serve static assets inside web_dir with path traversal protection.""" | |
| rel = self.path.split("?", 1)[0].split("#", 1)[0].lstrip("/") | |
| if not rel: | |
| rel = "index.html" | |
| root = web_dir.resolve() | |
| target = (root / rel).resolve() | |
| try: | |
| target.relative_to(root) | |
| except ValueError: | |
| self.send_json(403, {"error": "Access denied."}) | |
| return | |
| if not target.is_file(): | |
| self.send_json(404, {"error": "File not found."}) | |
| return | |
| ctype = ( | |
| _STATIC_CONTENT_TYPES.get(target.suffix.lower()) | |
| or mimetypes.guess_type(str(target))[0] | |
| or "application/octet-stream" | |
| ) | |
| try: | |
| data = target.read_bytes() | |
| self.send_response(200) | |
| self.send_header("Content-Type", ctype) | |
| self.send_header("Content-Length", str(len(data))) | |
| self.send_cors_headers() | |
| self.end_headers() | |
| self.wfile.write(data) | |
| except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError): | |
| pass | |
| def log_message(self, format: str, *args: object) -> None: | |
| logger.info("%-6s %s", args[0] if args else "", args[1] if len(args) > 1 else "") | |
| def run_http_server( | |
| host: str, | |
| port: int, | |
| handler_cls: type[BaseHTTPRequestHandler], | |
| *, | |
| startup_messages: Sequence[str] = (), | |
| on_shutdown: Callable[[], None] | None = None, | |
| ) -> None: | |
| """Start a multithreaded HTTP server and handle clean shutdown on KeyboardInterrupt.""" | |
| server = ThreadingHTTPServer((host, port), handler_cls) | |
| for msg in startup_messages: | |
| logger.info("%s", msg) | |
| try: | |
| server.serve_forever() | |
| except KeyboardInterrupt: | |
| logger.info("Server stopped.") | |
| if on_shutdown is not None: | |
| on_shutdown() | |
| server.server_close() | |