Skip to content

Instantly share code, notes, and snippets.

@biancarosa
Last active September 24, 2016 14:46
Show Gist options
  • Save biancarosa/2cf8493e1410bcc3914db7975277e084 to your computer and use it in GitHub Desktop.
Save biancarosa/2cf8493e1410bcc3914db7975277e084 to your computer and use it in GitHub Desktop.
Falcon JSON Translator
# middlewares/json_translator.py
import json
import falcon
class JSONTranslatorMiddleware(object):
def process_request(self, req, resp):
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['doc'] = 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_response(self, req, resp, resource):
if 'result' not in req.context:
return
resp.body = json.dumps(req.context['result'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment