Source code for muffineer.middlewares.json_handling

import falcon
import json

from marshmallow import ValidationError


[docs]class RequireJSON(object):
[docs] def process_request(self, req, resp): if not req.client_accepts_json: raise falcon.HTTPNotAcceptable( 'This API only supports responses encoded as JSON.', href='http://docs.examples.com/api/json') if req.method in ('POST', 'PUT'): if 'application/json' not in req.content_type: raise falcon.HTTPUnsupportedMediaType( 'This API only supports requests encoded as JSON.', href='http://docs.examples.com/api/json')
[docs]class JSONTranslator(object): """ Serializes Json Object and optionally validates it with Marshmallow """
[docs] 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): # Nothing to do 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_422, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.')
[docs] def process_response(self, req, resp, resource): """ :param req: :param resp: :param resource: :return: """ if 'result' not in req.context: return resp.body = json.dumps(req.context['result'])
[docs] def process_resource(self, req, resp, resource, params): """Process the request after routing. Note: This method is only called when the request matches a route to a resource. :param req: Request object that will be passed to the routed responder. :param resp: Response object that will be passed to the responder. :param resource: Resource object to which the request was routed. :param params: A dict-like object representing any additional params derived from the route's URI template fields, that will be passed to the resource's responder method as keyword arguments. """ req_data = req.context.get('doc') or req.params try: schema = resource.schemas[req.method.lower()] except (AttributeError, IndexError, KeyError): return else: try: req.context['doc'] = schema().load(req_data) except ValidationError: raise falcon.HTTPError(falcon.HTTP_422, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.')