##// END OF EJS Templates
raise ValidationError in v4 validate...
MinRK -
Show More
@@ -1,66 +1,69 b''
1 1 # Copyright (c) IPython Development Team.
2 2 # Distributed under the terms of the Modified BSD License.
3 3
4 4 from __future__ import print_function
5 5 import json
6 6 import os
7 7
8 8 try:
9 from jsonschema import SchemaError
9 from jsonschema import ValidationError
10 10 from jsonschema import Draft4Validator as Validator
11 11 except ImportError as e:
12 12 verbose_msg = """
13 13
14 14 IPython notebook format depends on the jsonschema package:
15 15
16 16 https://pypi.python.org/pypi/jsonschema
17 17
18 18 Please install it first.
19 19 """
20 20 raise ImportError(str(e) + verbose_msg)
21 21
22 22
23 23 from .nbbase import nbformat, nbformat_schema
24 24 schema_path = os.path.join(
25 25 os.path.dirname(__file__), nbformat_schema,
26 26 )
27 27
28 validator = None
29
30 def _load_schema():
31 """Load the JSON schema into the global Validator"""
32 global validator
33 if validator is None:
34 # load the schema file
35 with open(schema_path, 'r') as fh:
36 schema_json = json.load(fh)
37
38 # create the validator
39 validator = Validator(schema_json)
40 return validator
28 41
29 42 def isvalid(nbjson, ref=None):
30 43 """Checks whether the given notebook JSON conforms to the current
31 44 notebook format schema. Returns True if the JSON is valid, and
32 45 False otherwise.
33 46
34 47 To see the individual errors that were encountered, please use the
35 48 `validate` function instead.
36 49 """
37
38 it = validate(nbjson, ref)
39 50 try:
40 it.next()
41 except StopIteration:
42 return True
43 else:
51 validate(nbjson, ref)
52 except ValidationError:
44 53 return False
54 else:
55 return True
45 56
46 57
47 58 def validate(nbjson, ref=None):
48 59 """Checks whether the given notebook JSON conforms to the current
49 60 notebook format schema.
50 61
51 Returns a generator for errors.
62 Raises ValidationError if not valid.
52 63 """
64 _load_schema()
53 65
54 # load the schema file
55 with open(schema_path, 'r') as fh:
56 schema_json = json.load(fh)
57
58 # create the validator
59 v = Validator(schema_json)
60
61 # return the iterator on errors
62 66 if ref:
63 errors = v.iter_errors(nbjson, {'$ref' : '#/definitions/%s' % ref})
67 return validator.validate(nbjson, {'$ref' : '#/definitions/%s' % ref})
64 68 else:
65 errors = v.iter_errors(nbjson)
66 return errors
69 return validator.validate(nbjson)
General Comments 0
You need to be logged in to leave comments. Login now