def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Karalkin
# Looking in error schema path for
# property that failed validation
# Schema example:
# {
# "type": "object",
# "properties": {
# "foo": {"type": "number"},
# "bar": {"type": "string"}
# }
# "required": ["foo", "bar"]
# }
#
# Related err.schema_path examples:
# ['required'],
# ['properties', 'foo', 'type']
if "properties" in path:
path.remove("properties")
key = path.popleft()
# If validation failed by missing property,
# then parse err.message to find property name
# as it always first word enclosed in quotes
if key == "required":
key = err.message.split("'")[1]
_errors[key].append(str(err))
if _errors:
_raise_exception(
web.HTTPBadRequest,
"Request is invalid; There are validation errors.",
_errors)
评论列表
文章目录