Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
"""Response objects returned by the router."""
|
|
|
|
import json
|
|
|
|
from errors import (
|
|
MethodNotAllowedError,
|
|
NotFoundError,
|
|
PayloadTooLargeError,
|
|
ValidationError,
|
|
)
|
|
|
|
CONTENT_TYPES = {
|
|
".html": "text/html; charset=utf-8",
|
|
".css": "text/css; charset=utf-8",
|
|
".js": "application/javascript; charset=utf-8",
|
|
".json": "application/json",
|
|
".csv": "text/csv; charset=utf-8",
|
|
".svg": "image/svg+xml",
|
|
".png": "image/png",
|
|
".ico": "image/x-icon",
|
|
}
|
|
|
|
|
|
class Response:
|
|
"""A JSON (or empty) HTTP response."""
|
|
|
|
def __init__(self, status, payload=None, headers=None):
|
|
self.status = status
|
|
self.payload = payload
|
|
self.headers = dict(headers or {})
|
|
if payload is None:
|
|
self.body = b""
|
|
self.content_type = None
|
|
else:
|
|
self.body = json.dumps(payload).encode("utf-8")
|
|
self.content_type = "application/json"
|
|
|
|
|
|
class FileResponse(Response):
|
|
"""A response with a pre-rendered body and an explicit content type."""
|
|
|
|
def __init__(self, status, body, content_type, headers=None):
|
|
self.status = status
|
|
self.payload = None
|
|
self.headers = dict(headers or {})
|
|
self.body = body
|
|
self.content_type = content_type
|
|
|
|
|
|
def error_response(exc):
|
|
"""Map a known application error to a response, or None if it is unexpected."""
|
|
if isinstance(exc, ValidationError):
|
|
return Response(400, {"error": str(exc)})
|
|
if isinstance(exc, PayloadTooLargeError):
|
|
return Response(413, {"error": str(exc)})
|
|
if isinstance(exc, NotFoundError):
|
|
return Response(404, {"error": str(exc)})
|
|
if isinstance(exc, MethodNotAllowedError):
|
|
return Response(405, {"error": str(exc)}, {"Allow": ", ".join(exc.allowed)})
|
|
return None
|