-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathdemo_flaskrestjsonapi.py
executable file
·168 lines (131 loc) · 4.78 KB
/
demo_flaskrestjsonapi.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
This demo application demonstrates the functionality of the safrs documented JSON APIs with Flask-Rest-JSONAPI library.
After installing safrs and flask-rest-jsonapi with pip, you can run this app standalone:
$ python3 demo_flaskrestjsonapi.py [Listener-IP]
This will run the example on http://Listener-Ip:5010
- A database is created and items are added
- A Flask-rest-json api is available
- swagger documentation is generated
"""
from flask import Flask
from safrs import SAFRSBase, SafrsApi
from flask_rest_jsonapi import Api, ResourceDetail, ResourceList, ResourceRelationship
from flask_rest_jsonapi.exceptions import ObjectNotFound
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
from marshmallow_jsonapi.flask import Schema, Relationship
from marshmallow_jsonapi import fields
db = SQLAlchemy()
# Create data storage
class Person(db.Model, SAFRSBase):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
birth_date = db.Column(db.Date)
password = db.Column(db.String)
class Computer(db.Model, SAFRSBase):
id = db.Column(db.Integer, primary_key=True)
serial = db.Column(db.String)
person_id = db.Column(db.Integer, db.ForeignKey("person.id"))
person = db.relationship("Person", backref=db.backref("computers"))
# Create logical data abstraction (same as data storage for this first example)
class PersonSchema(Schema):
class Meta:
type_ = "person"
self_view = "person_detail"
self_view_kwargs = {"id": "<id>"}
self_view_many = "person_list"
id = fields.Integer(as_string=True, dump_only=True)
name = fields.Str(required=True, load_only=True)
email = fields.Email(load_only=True)
birth_date = fields.Date()
display_name = fields.Function(lambda obj: f"{obj.name.upper()} <{obj.email}>")
computers = Relationship(
self_view="person_computers",
self_view_kwargs={"id": "<id>"},
related_view="computer_list",
related_view_kwargs={"id": "<id>"},
many=True,
schema="ComputerSchema",
type_="computer",
)
class ComputerSchema(Schema):
class Meta:
type_ = "computer"
self_view = "computer_detail"
self_view_kwargs = {"id": "<id>"}
id = fields.Integer(as_string=True, dump_only=True)
serial = fields.Str(required=True)
owner = Relationship(
attribute="person",
self_view="computer_person",
self_view_kwargs={"id": "<id>"},
related_view="person_detail",
related_view_kwargs={"id": "<id>"},
schema="PersonSchema",
type_="person",
)
# Create resource managers
class PersonList(ResourceList):
schema = PersonSchema
data_layer = {"session": db.session, "model": Person}
class PersonDetail(ResourceDetail):
schema = PersonSchema
data_layer = {
"session": db.session,
"model": Person,
}
class PersonRelationship(ResourceRelationship):
schema = PersonSchema
data_layer = {"session": db.session, "model": Person}
class ComputerList(ResourceList):
schema = ComputerSchema
data_layer = {
"session": db.session,
"model": Computer,
}
class ComputerDetail(ResourceDetail):
schema = ComputerSchema
data_layer = {"session": db.session, "model": Computer}
class ComputerRelationship(ResourceRelationship):
schema = ComputerSchema
data_layer = {"session": db.session, "model": Computer}
# Create endpoints
def create_api(app, HOST="localhost", PORT=5010, API_PREFIX=""):
api = SafrsApi(app, host=HOST, port=PORT, prefix=API_PREFIX)
api.expose_object(Person)
api.expose_object(Computer)
print(f"Starting API: http://{HOST}:{PORT}/{API_PREFIX}")
def create_app(config_filename=None, host="localhost"):
app = Flask(__name__)
# app.config.update(SQLALCHEMY_DATABASE_URI="sqlite://")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db.init_app(app)
api = Api(app)
api.route(PersonList, "person_list", "/persons")
api.route(PersonDetail, "person_detail", "/persons/<int:id>", "/computers/<int:id>/owner")
api.route(
PersonRelationship,
"person_computers",
"/persons/<int:id>/relationships/computers",
)
api.route(
ComputerList,
"computer_list",
"/computers",
"/persons/<int:person_id>/computers",
)
api.route(ComputerDetail, "computer_detail", "/computers/<int:id>")
api.route(
ComputerRelationship,
"computer_person",
"/computers/<int:id>/relationships/owner",
)
with app.app_context():
db.create_all()
create_api(app, host)
return app
app = create_app(host="localhost")
if __name__ == "__main__":
# Start application
app.run(port=5010)