Exemple #1
0
    def get_parameters(
        self,
        req: falcon.Request,
        schema: marshmallow.Schema
    ):
        """ Decodes the body of incoming requests via a `marshmallow` schema
            and returns the result.

        Args:
            req (falcon.Request): The Falcon `Request` object.
            schema (marshmallow.Schema): The marshmallow schema instance that
                will be used to decode the body.
        """

        try:
            request_json = req.stream.read()
        except Exception as exc:
            msg_fmt = "Could not retrieve JSON body."
            self.logger.exception(msg_fmt)
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title="InvalidRequest",
                description=msg_fmt,
            )

        try:
            if request_json:
                # If the JSON body came through as `bytes` it needs to be
                # decoded into a `str`.
                if isinstance(request_json, bytes):
                    request_json = request_json.decode("utf-8")
                # Decode the JSON body through the `marshmallow` schema.
                parameters = schema.loads(request_json).data
            else:
                parameters = {}
        except marshmallow.ValidationError as exc:
            msg_fmt = "Response body violates schema."
            self.logger.exception(msg_fmt)
            raise falcon.HTTPError(
                status=falcon.HTTP_422,
                title="Schema violation.",
                description=msg_fmt + " Exception: {0}".format(str(exc))
            )
        except Exception as exc:
            msg_fmt = "Could not decode JSON body '{}'.".format(request_json)
            self.logger.exception(msg_fmt)
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title="InvalidRequest",
                description=msg_fmt + ". Exception: {0}".format(str(exc))
            )

        return parameters
Exemple #2
0
    def json(cls, *, response: Response,
             schema: m.Schema) -> 'PaddockResponse[Any]':
        """
        Create a response whose body is deserialized lazily as JSON with the
        body() function according to the given schema.

        :param response: the response to wrap
        :param schema: the schema to use to deserialize the body
        :return: the wrapped response
        """
        text = response.text
        return PaddockResponse(response=response,
                               converter=lambda: schema.loads(text))
Exemple #3
0
    def deserialize(json_string: str,
                    class_type: Type[T],
                    schema: Schema = None) -> T:
        if schema is not None:
            dictionary = schema.loads(json_data=json_string)
            if not isinstance(dictionary, list):
                return class_type(**dictionary)
            else:
                lstObject = list()
                for item in dictionary:
                    lstObject.append(class_type(**item))
                return lstObject

        return jsons.loads(json_string, class_type)
def de(schema: ms.Schema, data: str):
    return schema.loads(data)
Exemple #5
0
def _assert_dump_load(
    schema: marshmallow.Schema, loaded: t.Any, dumped: t.Dict[t.Any, t.Any]
) -> None:
    assert schema.loads(schema.dumps(loaded)) == loaded