1#!/usr/bin/env python 2 3from validictory.validator import (SchemaValidator, FieldValidationError, MultipleValidationError, 4 ValidationError, SchemaError) 5 6__all__ = ['validate', 'SchemaValidator', 'FieldValidationError', 'MultipleValidationError', 7 'ValidationError', 'SchemaError'] 8__version__ = '1.1.2' 9 10 11def validate(data, schema, validator_cls=SchemaValidator, 12 format_validators=None, required_by_default=True, 13 blank_by_default=False, disallow_unknown_properties=False, 14 apply_default_to_data=False, fail_fast=True, 15 remove_unknown_properties=False): 16 ''' 17 Validates a parsed json document against the provided schema. If an 18 error is found a :class:`ValidationError` is raised. 19 20 If there is an issue in the schema a :class:`SchemaError` will be raised. 21 22 :param data: python data to validate 23 :param schema: python dictionary representing the schema (see 24 `schema format`_) 25 :param validator_cls: optional validator class (default is 26 :class:`SchemaValidator`) 27 :param format_validators: optional dictionary of custom format validators 28 :param required_by_default: defaults to True, set to False to make 29 ``required`` schema attribute False by default. 30 :param disallow_unknown_properties: defaults to False, set to True to 31 disallow properties not listed in the schema definition 32 :param apply_default_to_data: defaults to False, set to True to modify the 33 data in case the schema definition includes a "default" property 34 :param fail_fast: defaults to True, set to False if you prefer to get 35 all validation errors back instead of only the first one 36 :param remove_unknown_properties: defaults to False, set to True to 37 filter out properties not listed in the schema definition. Only applies 38 when disallow_unknown_properties is False. 39 ''' 40 v = validator_cls(format_validators, required_by_default, blank_by_default, 41 disallow_unknown_properties, apply_default_to_data, fail_fast, 42 remove_unknown_properties) 43 return v.validate(data, schema) 44 45if __name__ == '__main__': 46 import sys 47 import json 48 if len(sys.argv) == 2: 49 if sys.argv[1] == "--help": 50 raise SystemExit("%s SCHEMAFILE [INFILE]" % (sys.argv[0],)) 51 schemafile = open(sys.argv[1], 'rb') 52 infile = sys.stdin 53 elif len(sys.argv) == 3: 54 schemafile = open(sys.argv[1], 'rb') 55 infile = open(sys.argv[2], 'rb') 56 else: 57 raise SystemExit("%s SCHEMAFILE [INFILE]" % (sys.argv[0],)) 58 try: 59 obj = json.load(infile) 60 schema = json.load(schemafile) 61 validate(obj, schema) 62 except ValueError as e: 63 raise SystemExit(e) 64