def validate_json(request):
    """Validates the request payload contains a valid JSON.

    Parameters
    ----------
    request : request
        POST request

    Raises
    ------
    *400* `Bad Request`
        Raise if the browser sends something to the application the application
    or server cannot handle.
    *415* `Unsupported Media Type`
        The status code returned if the server is unable to handle the media type
    the client transmitted.

    Returns
    -------
    json_payload : dict
        validated json
    """
    if not request.is_json:
        print("Warning! Bad content-type '{}' in payload".format(
            request.content_type))
        raise UnsupportedMediaType
    try:
        json_payload = request.get_json()
        return json_payload
    except Exception as e:
        bad_request_error = BadRequest()
        bad_request_error.description = '{}'.format(e)
        raise bad_request_error
Пример #2
0
def check_fields(data: dict, scheme: dict):
    ex = BadRequest()
    if not data:
        ex.description = "Body is empty or wrong content type"
        raise ex

    for name, props in scheme.items():
        if props['default']:
            data.setdefault(name, props["default"])

        if props['required']:
            if not data.get(name):
                ex.description = f"{name} is required"
                raise ex
            if props['type'] and type(data.get(name)) != props['type']:
                ex.description = f"{name} type is not {props['type']}"
                raise ex

        if props['validator'] and not props['validator'](data.get(name)):
            ex.description = f"{name}({data.get(name)}) did not pass validator"
            raise ex
Пример #3
0
def abort(message):
    resp = BadRequest()
    resp.description=message
    return resp