A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.

0 downloads

dbbasic-web/dbbasic_web/responses.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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"""
2from typing import Iterable
3from datetime import datetime
4
5
6def 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
14def 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
23def 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
54def 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
59def redirect(location: str, status: int = 302):
60 """Return redirect response"""
61 return status, [("location", location)], [b""]
62
63
64def 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
77def now_iso() -> str:
78 """Return current UTC time in ISO format"""
79 return datetime.utcnow().isoformat() + "Z"