Created
October 23, 2015 17:18
-
-
Save lbenitez000/4e3703f0de4d5d426fd6 to your computer and use it in GitHub Desktop.
A payload parser middleware for the Falcon Framework <http://falconframework.org/>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" A payload parser middleware for the Falcon Framework <http://falconframework.org/> | |
Currently it only works with Content-Type: application/json. | |
It is easily extendable for other Content-Types | |
""" | |
__author__ = "Luis Benitez" | |
__license__ = "MIT" | |
import falcon | |
import json | |
class PayloadParserMiddleware(object): | |
"""Parses the request body into Request.context['payload'] based on Request.content_type""" | |
def process_request(self, req, resp): | |
"""Process request""" | |
# Do nothing if there is no content_type | |
if req.content_type is None: | |
return | |
# Check if application/json is in content_type | |
if req.method in ['POST', 'PUT', 'PATCH'] and 'application/json' in req.content_type: | |
try: | |
data = json.load(req.stream) | |
except ValueError: | |
title = "Wrong request payload format" | |
description = "Request's content-type is %s, but request's payload is not." % req.content_type | |
raise falcon.HTTPBadRequest(title, description) | |
req.context['payload'] = data | |
else: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment