Created
November 30, 2017 21:05
-
-
Save mitsuhiko/8090d3bb54b35a67aed01f2e00129c46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_validator(): | |
default_class = jsonschema.Draft4Validator | |
validate_properties = default_class.VALIDATORS['properties'] | |
def handle_props(validator, properties, instance, schema): | |
for property, subschema in properties.items(): | |
if 'default' in subschema: | |
instance.setdefault(property, subschema['default']) | |
for key in list(instance.keys()): | |
if key not in properties: | |
del instance[key] | |
for error in validate_properties(validator, properties, instance, schema): | |
yield error | |
return jsonschema.validators.extend( | |
default_class, {'properties': handle_props}) | |
Validator = create_validator() | |
def validate_and_normalize(schema, data): | |
"""Validates data and modifies it in place.""" | |
Validator(schema).validate(data) | |
return data | |
def get_validated_json(schema): | |
"""Applies the request input JSON to the schema.""" | |
return validate_and_normalize(schema, request.get_json() or {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment