summaryrefslogtreecommitdiff
path: root/README.md
blob: 8aaadc86f3c9c946860c929ee14d2adb428000d3 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Warlock

**Create self-validating Python objects using JSON schema.**

[![PyPI](https://img.shields.io/pypi/v/warlock.svg)][warlock]
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/warlock.svg)][warlock]
[![PyPI - Downloads](https://img.shields.io/pypi/dw/warlock.svg)][pypistats]

[![Build Status](https://travis-ci.org/bcwaldon/warlock.svg?branch=master)][ci-builds]
[![Coverage Status](https://coveralls.io/repos/github/bcwaldon/warlock/badge.svg?branch=master)][coveralls]
![GitHub commits since latest release (branch)](https://img.shields.io/github/commits-since/bcwaldon/warlock/latest/master.svg)

[![Package management: poetry](https://img.shields.io/badge/deps-poetry-blueviolet.svg)][poetry]
[![Code Style Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black/)

## Installation

Warlock is [available on PyPI][warlock]:

```shell
pip install warlock
```

## Usage

1) Create your schema

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

2) Create a model

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

3) Create an object using your model

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

4) Let the object validate itself

    ```python
    >>> 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

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

[warlock]: https://pypi.org/project/warlock/
[pip]: https://pip.pypa.io/en/stable/
[ci-builds]: https://travis-ci.org/bcwaldon/warlock
[coveralls]: https://coveralls.io/github/bcwaldon/warlock?branch=master
[poetry]: https://poetry.eustace.io/docs/
[pypistats]: https://pypistats.org/packages/warlock