This repository was archived by the owner on Nov 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.py
More file actions
75 lines (60 loc) · 2.01 KB
/
middleware.py
File metadata and controls
75 lines (60 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'''
Json middleware for Falcon
Source: https://eshlox.net/2017/08/02/falcon-framework-json-middleware-loads-dumps/
'''
import datetime
import decimal
import json
import falcon
def json_serializer(obj):
if isinstance(obj, datetime.datetime):
return str(obj)
elif isinstance(obj, decimal.Decimal):
return str(obj)
raise TypeError("Cannot serialize {!r} (type {})".format(obj, type(obj)))
class JSONTranslator:
# def __init__(self):
# pass
def process_request(self, req, resp):
"""
req.stream corresponds to the WSGI wsgi.input environ variable,
and allows you to read bytes from the request body.
See also: PEP 3333
"""
if req.content_length in (None, 0):
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest(
"Empty request body. A valid JSON document is required."
)
try:
req.context["request"] = json.loads(body.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(
falcon.HTTP_753,
"Malformed JSON. Could not decode the request body."
"The JSON was incorrect or not encoded as UTF-8."
)
def process_resource(self, req, resp, resource, params):
fail = False
uri = req.relative_uri
addr = req.remote_addr
agent = req.user_agent
if "request" in req.context:
request = str(req.context["request"])
else:
request = ""
fail = True
method = req.method
if fail:
raise falcon.HTTPBadRequest(
"Empty request body. A valid JSON document is required."
)
def process_response(self, req, resp, resource, req_succeeded):
if "response" not in resp.context:
return
resp.body = json.dumps(
resp.context["response"],
default=json_serializer
)