blob: 205c221d883c0fd36db73fff7af02c9cc64a85d5 (
plain)
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
56
57
|
"""Core Warlock functionality"""
import copy
import jsonschema
class InvalidOperation(RuntimeError):
pass
class ValidationError(ValueError):
pass
def model_factory(schema):
"""Generate a model class based on the provided JSON Schema
:param schema: dict representing valid JSON schema
"""
schema = copy.deepcopy(schema)
def validator(obj):
"""Apply a JSON schema to an object"""
try:
jsonschema.validate(obj, schema)
except jsonschema.ValidationError:
raise ValidationError()
class Model(object):
"""Self-validating model for arbitrary objects"""
def __init__(self, **kwargs):
self.__dict__['validator'] = validator
try:
self.__dict__['validator'](kwargs)
except ValidationError:
raise ValueError()
else:
self.__dict__['raw'] = kwargs
def __getattr__(self, key):
try:
return self.__dict__['raw'][key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
mutation = copy.deepcopy(self.__dict__['raw'])
mutation[key] = value
try:
self.__dict__['validator'](mutation)
except ValidationError:
raise InvalidOperation()
self.__dict__['raw'] = mutation
Model.__name__ = str(schema['name'])
return Model
|