-
Notifications
You must be signed in to change notification settings - Fork 2
/
example.py
71 lines (49 loc) · 1.62 KB
/
example.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
import random
import string
import peewee as pw
from fastapi import FastAPI
from fastapiwee import AutoFastAPIViewSet
DB = pw.SqliteDatabase('/tmp/fastapiwee_example.db')
class ParentTestModel(pw.Model):
id = pw.AutoField()
text = pw.TextField()
class Meta:
database = DB
class TestModel(pw.Model):
id = pw.AutoField()
text = pw.TextField()
number = pw.IntegerField(null=True)
is_test = pw.BooleanField(default=True)
related = pw.ForeignKeyField(ParentTestModel, backref='test_models')
class Meta:
database = DB
class ChildTestModel(pw.Model):
id = pw.AutoField()
test = pw.ForeignKeyField(TestModel, backref='childs')
class Meta:
database = DB
def create_dummy_data(amount=10, childs=5):
DB.create_tables((ParentTestModel, TestModel, ChildTestModel))
rel_tm = ParentTestModel.create(
text='Parent Test',
)
for _ in range(amount):
tm = TestModel.create(
text=f'Test {"".join(random.choices(string.ascii_letters, k=8))}',
number=random.randint(0, 1e10),
is_test=bool(random.getrandbits(1)),
related=rel_tm,
)
for _ in range(childs):
ChildTestModel.create(
test=tm,
)
def drop_dummy_data():
DB.drop_tables((ParentTestModel, TestModel, ChildTestModel))
DB.close()
os.remove(DB.database)
app = FastAPI(on_startup=(create_dummy_data,), on_shutdown=(drop_dummy_data,))
AutoFastAPIViewSet(TestModel, app)
AutoFastAPIViewSet(ParentTestModel, app)
AutoFastAPIViewSet(ChildTestModel, app, actions={'create', 'retrieve'})