/
schema.py
55 lines (39 loc) · 1.23 KB
/
schema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""JSON Schema utilities
Attributes:
cache: Cache of previously loaded schemas
Resources:
http://json-schema.org/
http://json-schema.org/latest/json-schema-core.html
http://spacetelescope.github.io/understanding-json-schema/index.html
"""
import os
import json
import jsonschema
from .vendor import six
cache = {}
module_dir = os.path.dirname(__file__)
schema_dir = os.path.join(module_dir, "schema")
def load_all():
for schema in os.listdir(schema_dir):
if schema.startswith(("_", ".")):
continue
if not schema.endswith(".json"):
continue
if not os.path.isfile(os.path.join(schema_dir, schema)):
continue
with open(os.path.join(schema_dir, schema)) as f:
cache[schema] = json.load(f)
def validate(data, schema):
if isinstance(schema, six.string_types):
schema = cache[schema + ".json"]
resolver = jsonschema.RefResolver(
"",
None,
store=cache,
cache_remote=True)
return jsonschema.validate(data, schema, types={"array": (list, tuple)},
resolver=resolver)
ValidationError = jsonschema.ValidationError
load_all()
__all__ = ["validate",
"ValidationError"]