Debian Codegraph @

examples/validation.py

raw symbols SCIP
1 """
2 Example of JSON body validation in POST with various kinds of specs and views.
3 """
4 try:
5 from http import HTTPStatus
6 except ImportError:
7 import httplib as HTTPStatus
8 from flask import Blueprint
9 from flask import Flask
10 from flask import jsonify
11 from flask import request
12 from flasgger import Schema
13 from flasgger import Swagger
14 from flasgger import SwaggerView
15 from flasgger import fields
16 from flasgger import swag_from
17 from flasgger import validate
18 from flasgger import utils
19
20 # Examples include intentionally invalid defaults to demonstrate validation.
21 _TEST_META_SKIP_FULL_VALIDATION = True
22
23 app = Flask(__name__)
24 swag = Swagger(app)
25
26
27 test_specs_1 = {
28 "tags": [
29 "users"
30 ],
31 "parameters": [
32 {
33 "name": "body",
34 "in": "body",
35 "required": True,
36 "schema": {
37 "id": "User",
38 "required": [
39 "username",
40 "age"
41 ],
42 "properties": {
43 "username": {
44 "type": "string",
45 "description": "The user name.",
46 "default": "Sirius Black"
47 },
48 "age": {
49 "type": "integer",
50 "description": "The user age (should be integer)",
51 "default": "180"
52 },
53 "tags": {
54 "type": "array",
55 "description": "optional list of tags",
56 "default": [
57 "wizard",
58 "hogwarts",
59 "dead"
60 ],
61 "items": {
62 "type": "string"
63 }
64 }
65 }
66 }
67 }
68 ],
69 "responses": {
70 "200": {
71 "description": "A single user item",
72 "schema": {
73 "$ref": "#/definitions/User"
74 }
75 }
76 }
77 }
78
79
80 @app.route("/manualvalidation", methods=['POST'])
81 @swag_from("test_validation.yml")
82 def manualvalidation():
83 """
84 In this example you need to call validate() manually
85 passing received data, Definition (schema: id), specs filename
86 """
87 data = request.json
88 validate(data, 'User', "test_validation.yml")
89 return jsonify(data)
90
91
92 @app.route("/validateannotation", methods=['POST'])
93 @swag.validate('User')
94 @swag_from("test_validation.yml")
95 def validateannotation():
96 """
97 In this example you use validate(schema_id) annotation on the
98 method in which you want to validate received data
99 """
100 data = request.json
101 return jsonify(data)
102
103
104 @app.route("/autovalidation", methods=['POST'])
105 @swag_from("test_validation.yml", validation=True)
106 def autovalidation():
107 """
108 Example using auto validation from yaml file.
109 In this example you don't need to call validate() because
110 `validation=True` on @swag_from does that for you.
111 In this case it will use the same provided filename
112 and will extract the schema from `in: body` definition
113 and the data will default to `request.json`
114
115 or you can specify:
116 @swag_from('file.yml',
117 validation=True,
118 definition='User',
119 data=lambda: request.json, # any callable
120 )
121 """
122 data = request.json
123 return jsonify(data)
124
125
126 @app.route("/autovalidationfromspecdict", methods=['POST'])
127 @swag_from(test_specs_1, validation=True)
128 def autovalidation_from_spec_dict():
129 """
130 Example using data from dict to validate.
131 In this example you don't need to call validate() because
132 `validation=True` on @swag_from does that for you.
133 In this case it will use the same provided filename
134 and will extract the schema from `in: body` definition
135 and the data will default to `request.json`
136
137 or you can specify:
138 @swag_from('file.yml',
139 validation=True,
140 definition='User',
141 data=lambda: request.json, # any callable
142 )
143 """
144 data = request.json
145 return jsonify(data)
146
147
148 class User(Schema):
149 username = fields.Str(required=True, default="Sirius Black")
150 # wrong default "180" to force validation error
151 age = fields.Int(required=True, min=18, default="180")
152 tags = fields.List(fields.Str(), default=["wizard", "hogwarts", "dead"])
153
154
155 class UserPostView(SwaggerView):
156 tags = ['users']
157 parameters = User
158 responses = {
159 200: {
160 'description': 'A single user item',
161 'schema': User
162 }
163 }
164 validation = True
165
166 def post(self):
167 """
168 Example using marshmallow Schema
169 validation=True forces validation of parameters in body
170 ---
171 # This value overwrites the attributes above
172 deprecated: true
173 """
174 return jsonify(request.json)
175
176
177 app.add_url_rule(
178 '/schemevalidation',
179 view_func=UserPostView.as_view('schemevalidation'),
180 methods=['POST']
181 )
182
183
184 # ensure the same works for blueprints
185
186 example_blueprint = Blueprint(
187 "example", __name__, url_prefix='/blueprint')
188
189
190 @example_blueprint.route("/autovalidationfromdocstring", methods=['POST'])
191 @swag.validate('Officer')
192 def autovalidation_from_docstring():
193 """
194 Test validation using JsonSchema
195
196 The default payload is invalid, try it, then change the age to a
197 valid integer and try again
198 ---
199 tags:
200 - officer
201 parameters:
202 - name: body
203 in: body
204 required: true
205 schema:
206 id: Officer
207 required:
208 - name
209 - age
210 properties:
211 name:
212 type: string
213 description: The officer's name.
214 default: "James T. Kirk"
215 age:
216 type: integer
217 description: The officer's age (should be integer)
218 default: "138"
219 tags:
220 type: array
221 description: optional list of tags
222 default: ["starfleet", "captain", "enterprise", "dead"]
223 items:
224 type: string
225
226 responses:
227 200:
228 description: A single officer item
229 schema:
230 $ref: '#/definitions/Officer'
231 """
232 data = request.json
233 return jsonify(data)
234
235
236 @example_blueprint.route('/manualvalidation', methods=['POST'])
237 @swag_from("test_validation.yml")
238 def manualvalidation_bp():
239 """
240 In this example you need to call validate() manually
241 passing received data, Definition (schema: id), specs filename
242 """
243 data = request.json
244 validate(data, 'User', "test_validation.yml")
245 return jsonify(data)
246
247
248 @example_blueprint.route('/autovalidation', methods=['POST'])
249 @swag_from("test_validation.yml", validation=True)
250 def autovalidation_bp():
251 """
252 Example using auto validation from yaml file.
253 In this example you don't need to call validate() because
254 `validation=True` on @swag_from does that for you.
255 In this case it will use the same provided filename
256 and will extract the schema from `in: body` definition
257 and the data will default to `request.json`
258
259 or you can specify:
260 @swag_from('file.yml',
261 validation=True,
262 definition='User',
263 data=lambda: request.json, # any callable
264 )
265 """
266 data = request.json
267 return jsonify(data)
268
269
270 @example_blueprint.route("/autovalidationfromspecdict", methods=['POST'])
271 @swag_from(test_specs_1, validation=True)
272 def autovalidation_from_spec_dict_bp():
273 """
274 Example using data from dict to validate.
275 In this example you don't need to call validate() because
276 `validation=True` on @swag_from does that for you.
277 In this case it will use the same provided filename
278 and will extract the schema from `in: body` definition
279 and the data will default to `request.json`
280
281 or you can specify:
282 @swag_from('file.yml',
283 validation=True,
284 definition='User',
285 data=lambda: request.json, # any callable
286 )
287 """
288 data = request.json
289 return jsonify(data)
290
291
292 class BPUserPostView(SwaggerView):
293 tags = ['users']
294 parameters = User
295 responses = {
296 200: {
297 'description': 'A single user item',
298 'schema': User
299 }
300 }
301 validation = True
302
303 def post(self):
304 """
305 Example using marshmallow Schema
306 validation=True forces validation of parameters in body
307 ---
308 # This value overwrites the attributes above
309 deprecated: true
310 """
311 return jsonify(request.json)
312
313
314 example_blueprint.add_url_rule(
315 '/schemevalidation',
316 view_func=BPUserPostView.as_view('schemevalidation'),
317 methods=['POST']
318 )
319
320
321 app.register_blueprint(example_blueprint)
322
323
324 def test_swag(client, specs_data):
325 """
326 This test is runs automatically in Travis CI
327
328 :param client: Flask app test client
329 :param specs_data: {'url': {swag_specs}} for every spec in app
330 """
331
332 apispec = specs_data.get('/apispec_1.json')
333
334 assert apispec is not None
335
336 paths = apispec.get('paths')
337
338 expected_user_paths = (
339 '/autovalidation',
340 '/validateannotation',
341 '/autovalidationfromspecdict',
342 '/blueprint/autovalidation',
343 '/blueprint/autovalidationfromspecdict',
344 '/blueprint/manualvalidation',
345 '/blueprint/schemevalidation',
346 '/manualvalidation',
347 '/schemevalidation',
348 )
349
350 expected_officer_paths = (
351 '/blueprint/autovalidationfromdocstring',
352 )
353
354 invalid_users = (
355 """
356 {
357 "username": "Sirius Black",
358 "age": "180",
359 "tags": [
360 "wizard",
361 "hogwarts",
362 "dead"
363 ]
364 }
365 """,
366 """
367 {
368 "age": 180,
369 "tags": [
370 "wizard"
371 ]
372 }
373 """,
374 )
375
376 valid_users = (
377 """
378 {
379 "username": "Sirius Black",
380 "age": 180,
381 "tags": [
382 "wizard",
383 "hogwarts",
384 "dead"
385 ]
386 }
387 """,
388 """
389 {
390 "username": "Ronald Weasley",
391 "age": 22
392 }
393 """,
394 )
395
396 invalid_officers = (
397 """
398 {
399 "name": "James T. Kirk",
400 "age": "138",
401 "tags": [
402 "captain",
403 "enterprise",
404 "dead"
405 ]
406 }
407 """,
408 """
409 {
410 "age": 138,
411 "tags": [
412 "captain"
413 ]
414 }
415 """,
416 )
417
418 valid_officers = (
419 """
420 {
421 "name": "James T. Kirk",
422 "age": 138,
423 "tags": [
424 "captain",
425 "enterprise",
426 "dead"
427 ]
428 }
429 """,
430 """
431 {
432 "name": "Jean-Luc Picard",
433 "age": 60
434 }
435 """,
436 )
437
438 assert paths is not None and len(paths) > 0
439
440 definitions = utils.extract_schema(apispec)
441
442 assert definitions is not None
443 assert definitions.get('User') is not None
444 assert definitions.get('Officer') is not None
445
446 for expected_path in expected_user_paths:
447 assert paths.get(expected_path) is not None
448
449 for invalid_user in invalid_users:
450 response = client.post(
451 expected_path, data=invalid_user,
452 content_type='application/json')
453 assert response.status_code == HTTPStatus.BAD_REQUEST
454
455 for valid_user in valid_users:
456 response = client.post(
457 expected_path, data=valid_user,
458 content_type='application/json')
459 assert response.status_code == HTTPStatus.OK
460
461 for expected_path in expected_officer_paths:
462 assert paths.get(expected_path) is not None
463
464 for invalid_officer in invalid_officers:
465 response = client.post(
466 expected_path, data=invalid_officer,
467 content_type='application/json')
468 assert response.status_code == HTTPStatus.BAD_REQUEST
469
470 for valid_officer in valid_officers:
471 response = client.post(
472 expected_path, data=valid_officer,
473 content_type='application/json')
474 assert response.status_code == HTTPStatus.OK
475
476 if __name__ == "__main__":
477 app.run(debug=True)