askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
responses.py · 2.3 KB · 79 lines
| 1 | """Response helpers for various content types""" |
| 2 | from typing import Iterable |
| 3 | from datetime import datetime |
| 4 | |
| 5 | |
| 6 | def html(body: str, status: int = 200, headers: list[tuple[str, str]] | None = None): |
| 7 | """Return HTML response""" |
| 8 | h = [("content-type", "text/html; charset=utf-8")] |
| 9 | if headers: |
| 10 | h.extend(headers) |
| 11 | return status, h, [body.encode("utf-8")] |
| 12 | |
| 13 | |
| 14 | def json(body: bytes | str, status: int = 200, headers: list[tuple[str, str]] | None = None): |
| 15 | """Return JSON response""" |
| 16 | h = [("content-type", "application/json; charset=utf-8")] |
| 17 | if headers: |
| 18 | h.extend(headers) |
| 19 | b = body if isinstance(body, bytes) else body.encode("utf-8") |
| 20 | return status, h, [b] |
| 21 | |
| 22 | |
| 23 | def json_error(message: str, status: int = 404): |
| 24 | """ |
| 25 | Return JSON error response. |
| 26 | |
| 27 | Convenience helper that reduces verbose error handling: |
| 28 | |
| 29 | Before: |
| 30 | import json as json_lib |
| 31 | return json(json_lib.dumps({"error": "User not found"}), status=404) |
| 32 | |
| 33 | After: |
| 34 | return json_error("User not found", status=404) |
| 35 | |
| 36 | Example: |
| 37 | from dbbasic_web.responses import json_error |
| 38 | |
| 39 | def handle(request): |
| 40 | user_id = request.path_param(1) |
| 41 | if not user_id: |
| 42 | return json_error("User ID required", status=400) |
| 43 | |
| 44 | user = get_user(user_id) |
| 45 | if not user: |
| 46 | return json_error("User not found", status=404) |
| 47 | |
| 48 | return json(...) |
| 49 | """ |
| 50 | import json as json_lib |
| 51 | return json(json_lib.dumps({"error": message}), status=status) |
| 52 | |
| 53 | |
| 54 | def text(s: str, status: int = 200): |
| 55 | """Return plain text response""" |
| 56 | return status, [("content-type", "text/plain; charset=utf-8")], [s.encode("utf-8")] |
| 57 | |
| 58 | |
| 59 | def redirect(location: str, status: int = 302): |
| 60 | """Return redirect response""" |
| 61 | return status, [("location", location)], [b""] |
| 62 | |
| 63 | |
| 64 | def sse_event(data: str, event: str | None = None, id: str | None = None) -> bytes: |
| 65 | """Format a Server-Sent Event""" |
| 66 | lines = [] |
| 67 | if event: |
| 68 | lines.append(f"event: {event}") |
| 69 | if id: |
| 70 | lines.append(f"id: {id}") |
| 71 | for line in data.splitlines() or [""]: |
| 72 | lines.append(f"data: {line}") |
| 73 | lines.append("") # final newline |
| 74 | return ("\n".join(lines) + "\n").encode("utf-8") |
| 75 | |
| 76 | |
| 77 | def now_iso() -> str: |
| 78 | """Return current UTC time in ISO format""" |
| 79 | return datetime.utcnow().isoformat() + "Z" |