Debian Codegraph @

examples/validation_error_handler.py

raw symbols SCIP
1 import jsonschema
2 from jsonschema import ValidationError
3 from werkzeug.exceptions import abort
4 from flask import Flask
5 try:
6 from http import HTTPStatus
7 except ImportError:
8 import httplib as HTTPStatus
9 try:
10 import simplejson as json
11 except ImportError:
12 import json
13 from flask import jsonify
14 from flask import Response
15 from flask import request
16 from flasgger import Swagger
17
18
19 def validation_error_inform_error(err, data, schema):
20 """
21 Custom validation error handler which produces 404 Bad Request
22 response in case validation fails and returns the error
23 """
24 abort(Response(
25 json.dumps({'error': str(err), 'data': data, 'schema': schema}),
26 status=HTTPStatus.BAD_REQUEST))
27
28
29 def validation_error_404(err, data, schema):
30 """
31 Custom validation error handler which produces 404 Not Found
32 response in case validation fails instead of 400 Bad Request
33 """
34 abort(Response(status=HTTPStatus.NOT_FOUND))
35
36
37 def validation_error_try_to_accept(err, data, schema):
38 """
39 Custom validation error handler which attempts alternative
40 validation
41 """
42 if not isinstance(err, ValidationError):
43 abort(Response(err, status=HTTPStatus.BAD_REQUEST))
44
45 alernative_schema = dict(schema)
46 alernative_schema['properties']['running_time'].update({
47 'description': "Films's running time",
48 'type': 'integer',
49 'example': 169
50 })
51
52 try:
53 jsonschema.validate(data, alernative_schema)
54 except ValidationError as err:
55 abort(Response(str(err), status=400))
56
57
58 app = Flask(__name__)
59 swag = Swagger(app, validation_error_handler=validation_error_inform_error)
60
61
62 @app.route('/film', methods=['POST'])
63 @swag.validate('Film')
64 def create_film():
65 """
66 Film creation endpoint
67 ---
68 tags:
69 - film
70 summary: Creates a new Film
71 consumes:
72 - application/json
73 produces:
74 - application/json
75 parameters:
76 - in: body
77 name: body
78 description:
79 Film object that needs to be persisted to the database
80 required: true
81 schema:
82 id: Film
83 required:
84 - title
85 - director
86 - distributor
87 - release_date
88 - running_time
89 properties:
90 title:
91 description: Film's title
92 type: string
93 example: Interstellar
94 director:
95 description: Films's director
96 type: string
97 example: Christopher Nolan
98 distributor:
99 description: Films's distributor
100 type: string
101 example: Warner Bros. Pictures
102 release_date:
103 description: Films's release date
104 type: string
105 example: October 26, 2014
106 running_time:
107 description: Films's running time
108 type: string
109 example: 169 minutes
110 responses:
111 200:
112 description: Successful operation
113 400:
114 description: Invalid input
115 """
116 return jsonify(request.json), HTTPStatus.OK
117
118
119 @app.route('/not_found/film', methods=['POST'])
120 @swag.validate('Film', validation_error_handler=validation_error_404)
121 def create_film_2():
122 """
123 Film creation endpoint
124 ---
125 tags:
126 - film
127 summary: Creates a new Film
128 consumes:
129 - application/json
130 produces:
131 - application/json
132 parameters:
133 - in: body
134 name: body
135 description:
136 Film object that needs to be persisted to the database
137 required: true
138 schema:
139 $ref: '#/definitions/Film'
140 responses:
141 200:
142 description: Successful operation
143 400:
144 description: Invalid input
145 """
146 return jsonify(request.json), HTTPStatus.OK
147
148
149 @app.route('/retry/film', methods=['POST'])
150 @swag.validate('Film', validation_error_handler=validation_error_try_to_accept)
151 def create_film_3():
152 """
153 Film creation endpoint
154 ---
155 tags:
156 - film
157 summary: Creates a new Film
158 consumes:
159 - application/json
160 produces:
161 - application/json
162 parameters:
163 - in: body
164 name: body
165 description:
166 Film object that needs to be persisted to the database
167 required: true
168 schema:
169 $ref: '#/definitions/Film'
170 responses:
171 200:
172 description: Successful operation
173 400:
174 description: Invalid input
175 """
176 return jsonify(request.json), HTTPStatus.OK
177
178
179 def test_swag(client, specs_data):
180 """
181 This test is runs automatically in Travis CI
182
183 :param client: Flask app test client
184 :param specs_data: {'url': {swag_specs}} for every spec in app
185 """
186 invalid_film = {
187 '_id': "594dba7b2879334e411f3dcc",
188 'title': "The Last Airbender",
189 'director': "M. Night Shyamalan",
190 'distributor': "Paramount Pictures",
191 'running_time': 103,
192 'release_date': "June 30, 2010"
193 }
194
195 super_invalid_film = {
196 'title': "The Last Airbender",
197 'release_date': 2010
198 }
199
200 with client.post(
201 '/film', data=json.dumps(invalid_film),
202 content_type='application/json') as response:
203 assert response.status_code == HTTPStatus.BAD_REQUEST
204
205 received = json.loads(response.data.decode('utf-8'))
206 assert received.get('error') is not None
207 assert received.get('schema') is not None
208 assert received.get('data') == invalid_film
209
210 with client.post(
211 '/not_found/film', data=json.dumps(invalid_film),
212 content_type='application/json') as response:
213 assert response.status_code == HTTPStatus.NOT_FOUND
214
215 with client.post(
216 '/retry/film', data=json.dumps(invalid_film),
217 content_type='application/json') as response:
218 assert response.status_code == HTTPStatus.OK
219
220 with client.post(
221 '/retry/film', data=json.dumps(super_invalid_film),
222 content_type='application/json') as response:
223 assert response.status_code == HTTPStatus.BAD_REQUEST
224
225 if __name__ == "__main__":
226 app.run(debug=True)