This repository was archived by the owner on Jun 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathflask_example.py
More file actions
181 lines (128 loc) · 4.07 KB
/
Copy pathflask_example.py
File metadata and controls
181 lines (128 loc) · 4.07 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
from flask import Flask, request, jsonify
### MODELS ###
class Model:
def __init__(self, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
class Comment(Model):
pass
class Author(Model):
pass
class Post(Model):
pass
### MOCK DATABASE ###
comment1 = Comment(id=1, body="First!")
comment2 = Comment(id=2, body="I like XML better!")
author1 = Author(id=1, first_name="Dan", last_name="Gebhardt", twitter="dgeb")
post1 = Post(
id=1,
title="JSON API paints my bikeshed!",
author=author1,
comments=[comment1, comment2],
)
db = {"comments": [comment1, comment2], "authors": [author1], "posts": [post1]}
### SCHEMAS ###
from marshmallow import validate, ValidationError # noqa: E402
from marshmallow_jsonapi import fields # noqa: E402
from marshmallow_jsonapi.flask import Relationship, Schema # noqa: E402
class CommentSchema(Schema):
id = fields.Str(dump_only=True)
body = fields.Str()
class Meta:
type_ = "comments"
self_view = "comment_detail"
self_view_kwargs = {"comment_id": "<id>", "_external": True}
self_view_many = "comments_list"
class AuthorSchema(Schema):
id = fields.Str(dump_only=True)
first_name = fields.Str(required=True)
last_name = fields.Str(required=True)
password = fields.Str(load_only=True, validate=validate.Length(6))
twitter = fields.Str()
class Meta:
type_ = "people"
self_view = "author_detail"
self_view_kwargs = {"author_id": "<id>"}
self_view_many = "authors_list"
class PostSchema(Schema):
id = fields.Str(dump_only=True)
title = fields.Str()
author = Relationship(
related_view="author_detail",
related_view_kwargs={"author_id": "<author.id>", "_external": True},
include_data=True,
type_="people",
)
comments = Relationship(
related_view="posts_comments",
related_view_kwargs={"post_id": "<id>", "_external": True},
many=True,
include_data=True,
type_="comments",
)
class Meta:
type_ = "posts"
self_view = "posts_detail"
self_view_kwargs = {"post_id": "<id>"}
self_view_many = "posts_list"
### VIEWS ###
app = Flask(__name__)
app.config["DEBUG"] = True
def J(*args, **kwargs):
"""Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json.
"""
response = jsonify(*args, **kwargs)
response.mimetype = "application/vnd.api+json"
return response
@app.route("/posts/", methods=["GET"])
def posts_list():
posts = db["posts"]
data = PostSchema(many=True).dump(posts)
return J(data)
@app.route("/posts/<int:post_id>")
def posts_detail(post_id):
post = db["posts"][post_id - 1]
data = PostSchema().dump(post)
return J(data)
@app.route("/posts/<int:post_id>/comments/")
def posts_comments(post_id):
post = db["posts"][post_id - 1]
comments = post.comments
data = CommentSchema(many=True).dump(comments)
return J(data)
@app.route("/authors/")
def authors_list():
author = db["authors"]
data = AuthorSchema(many=True).dump(author)
return J(data)
@app.route("/authors/<int:author_id>")
def author_detail(author_id):
author = db["authors"][author_id - 1]
data = AuthorSchema().dump(author)
return J(data)
@app.route("/authors/", methods=["POST"])
def author_create():
schema = AuthorSchema()
input_data = request.get_json() or {}
try:
data = schema.load(input_data)
except ValidationError as err:
return J(err.messages), 422
id_ = len(db["authors"])
author = Author(id=id_, **data)
db["authors"].append(author)
data = schema.dump(author)
return J(data)
@app.route("/comments/")
def comments_list():
comment = db["comments"]
data = CommentSchema(many=True).dump(comment)
return J(data)
@app.route("/comments/<int:comment_id>")
def comment_detail(comment_id):
comment = db["comments"][comment_id - 1]
data = CommentSchema().dump(comment)
return J(data)
if __name__ == "__main__":
app.run()