Last active
April 8, 2020 21:34
-
-
Save jmborr/ebdf5b5893a7a40e08cce2d17175bfe2 to your computer and use it in GitHub Desktop.
jsonschema validators using more than one instance
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
class ReductionParameters: | |
_validators = {'twoone': '_validate_two_using_one'} | |
def __init__(self, reduction_parameters, schema): | |
self._parameters = reduction_parameters | |
self._schema = schema | |
self._json_validator = None | |
self._initialize_json_validator() | |
def _validate_two_using_one(self, validator, value, instance, schema): | |
one = self._parameters['one'] | |
if one + instance < value: | |
raise ValidationError(f'{instance} is not enough') | |
def _initialize_json_validator(self): | |
all_validators = dict(Draft7Validator.VALIDATORS) | |
for keyword, function_name in self._validators.items(): | |
function = getattr(self, function_name) # this is the key. "self" is not present in "function"'s signature | |
all_validators[keyword] = function | |
self._json_validator = validators.create(meta_schema=Draft7Validator.META_SCHEMA, validators=all_validators) | |
def validate(self): | |
jsonschema.validate(self._parameters, self._schema, cls=self._json_validator) | |
schema = r"""{ | |
"$schema": "http://json-schema.org/draft-07/schema#", | |
"type": "object", | |
"properties": { | |
"one": { | |
"type": "number" | |
}, | |
"two": { | |
"type": "number", | |
"twoone": 42 | |
} | |
} | |
} | |
""" | |
instance = {"one": 1, "two": 1} | |
redparms = ReductionParameters(instance, json.loads(schema)) | |
redparms.validate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment