def enforce_request_json_schema(schema, no_extra=False):
"""Decorator that throws an exception if the request data doesn't match the given schema
@param schema A one level deep dictionary that maps keys to types
@param no_extra A flag which asserts that the request data had no superflous keys
"""
def validate_data(data):
if no_extra and data.keys() > schema.keys():
return False
check_type = lambda key: isinstance(data[key], schema[key])
return all(map(check_type, schema.keys()))
def wraps(f):
def decorated(*args, **kwargs):
data = jsonpickle.decode(request.data.decode("utf-8"))
if not validate_data(data):
raise DecidePoliticsException(Errors.INVALID_DATA_PRESENT)
return f(*args, **kwargs)
return decorated
return wraps
评论列表
文章目录