summaryrefslogtreecommitdiff
path: root/README.md
blob: abba83e48fa882a4b30b4e0d025ffe09460b9e16 (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
# Warlock

[![Build Status](https://travis-ci.org/bcwaldon/warlock.svg?branch=master)](https://travis-ci.org/bcwaldon/warlock)

Build self-validating python objects using JSON schemas.

1) Create your schema

    >>> schema = {
        'name': 'Country',
        'properties': {
            'name': {'type': 'string'},
            'abbreviation': {'type': 'string'},
            'population': {'type': 'integer'},
        },
        'additionalProperties': False,
    }

2) Create a model

    >>> import warlock
    >>> Country = warlock.model_factory(schema)

3) Create an object using your model

    >>> sweden = Country(name='Sweden', abbreviation='SE')

4) Let the object validate itself

    >>> sweden.name = 5
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "warlock/core.py", line 53, in __setattr__
        raise InvalidOperation(msg)
    warlock.core.InvalidOperation: Unable to set 'name' to '5'

    >>> sweden.overlord = 'Bears'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "warlock/core.py", line 53, in __setattr__
        raise InvalidOperation(msg)
    warlock.core.InvalidOperation: Unable to set 'overlord' to 'Bears'

5) Generate a [JSON Patch document](http://tools.ietf.org/html/draft-ietf-appsawg-json-patch) to track changes

    >>> sweden.population=9453000
    >>> sweden.patch
    '[{"path": "/population", "value": 9453000, "op": "add"}]'