Skip to content

Commit 03e609b

Browse files
committed
Add simple example
1 parent 307fa80 commit 03e609b

File tree

4 files changed

+91
-0
lines changed

4 files changed

+91
-0
lines changed

examples/document.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"MyBook": {
3+
"title": "My life in Python",
4+
"pages": {
5+
"1": {},
6+
"2": {}
7+
}
8+
}
9+
}

examples/document.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from modelspec import *
2+
from modelspec.utils import *
3+
4+
# Example showing how to create a model of a document and use it to create/serialise instances
5+
6+
7+
class Document(BaseWithId):
8+
9+
_definition = "A model for documents"
10+
11+
def __init__(self, **kwargs):
12+
13+
self.allowed_children = collections.OrderedDict(
14+
[
15+
("pages", ("The pages", Page)),
16+
]
17+
)
18+
19+
self.allowed_fields = collections.OrderedDict(
20+
[
21+
("title", ("Document title", str)),
22+
(
23+
"ISBN",
24+
(
25+
"International Standard Book Number",
26+
int,
27+
),
28+
),
29+
]
30+
)
31+
32+
super(Document, self).__init__(**kwargs)
33+
34+
35+
class Page(BaseWithId):
36+
37+
_definition = "A model of a page"
38+
39+
def __init__(self, **kwargs):
40+
41+
self.allowed_children = collections.OrderedDict(
42+
[
43+
("lines", ("The pages", Line)),
44+
]
45+
)
46+
47+
super(Page, self).__init__(**kwargs)
48+
49+
50+
class Line(Base):
51+
52+
_definition = "A model of a line"
53+
54+
def __init__(self, **kwargs):
55+
56+
self.allowed_fields = collections.OrderedDict(
57+
[
58+
("title", ("Document title", str)),
59+
]
60+
)
61+
62+
63+
doc = Document(id="MyBook")
64+
doc.title = "My life in Python"
65+
66+
doc.pages.append(Page(id=1))
67+
doc.pages.append(Page(id=2))
68+
69+
print(doc)
70+
71+
doc.to_json_file("document.json")
72+
doc.to_yaml_file("document.yaml")

examples/document.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
MyBook:
2+
title: My life in Python
3+
pages:
4+
'1': {}
5+
'2': {}

test_all.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,10 @@ set -ex
33

44
pip install .
55

6+
cd examples
7+
python document.py
8+
9+
cd ..
10+
611
cd modelspec/test
712
pytest -v

0 commit comments

Comments
 (0)