File: validation_error_handler.py

package info (click to toggle)
python-flasgger 0.9.5%2Bdfsg.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 13,152 kB
  • sloc: javascript: 6,403; python: 3,665; makefile: 9; sh: 1
file content (226 lines) | stat: -rw-r--r-- 6,179 bytes parent folder | download | duplicates (3)
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import jsonschema
from jsonschema import ValidationError
from werkzeug.exceptions import abort
from flask import Flask
try:
    from http import HTTPStatus
except ImportError:
    import httplib as HTTPStatus
try:
    import simplejson as json
except ImportError:
    import json
from flask import jsonify
from flask import Response
from flask import request
from flasgger import Swagger


def validation_error_inform_error(err, data, schema):
    """
    Custom validation error handler which produces 404 Bad Request
    response in case validation fails and returns the error
    """
    abort(Response(
        json.dumps({'error': str(err), 'data': data, 'schema': schema}),
        status=HTTPStatus.BAD_REQUEST))


def validation_error_404(err, data, schema):
    """
    Custom validation error handler which produces 404 Not Found
    response in case validation fails instead of 400 Bad Request
    """
    abort(Response(status=HTTPStatus.NOT_FOUND))


def validation_error_try_to_accept(err, data, schema):
    """
    Custom validation error handler which attempts alternative
    validation
    """
    if not isinstance(err, ValidationError):
        abort(Response(err, status=HTTPStatus.BAD_REQUEST))

    alernative_schema = dict(schema)
    alernative_schema['properties']['running_time'].update({
        'description': "Films's running time",
        'type': 'integer',
        'example': 169
    })

    try:
        jsonschema.validate(data, alernative_schema)
    except ValidationError as err:
        abort(Response(str(err), status=400))


app = Flask(__name__)
swag = Swagger(app, validation_error_handler=validation_error_inform_error)


@app.route('/film', methods=['POST'])
@swag.validate('Film')
def create_film():
    """
    Film creation endpoint
    ---
    tags:
      - film
    summary: Creates a new Film
    consumes:
      - application/json
    produces:
      - application/json
    parameters:
      - in: body
        name: body
        description:
          Film object that needs to be persisted to the database
        required: true
        schema:
          id: Film
          required:
            - title
            - director
            - distributor
            - release_date
            - running_time
          properties:
            title:
              description: Film's title
              type: string
              example: Interstellar
            director:
              description: Films's director
              type: string
              example: Christopher Nolan
            distributor:
              description: Films's distributor
              type: string
              example: Warner Bros. Pictures
            release_date:
              description: Films's release date
              type: string
              example: October 26, 2014
            running_time:
              description: Films's running time
              type: string
              example: 169 minutes
    responses:
      200:
        description: Successful operation
      400:
        description: Invalid input
    """
    return jsonify(request.json), HTTPStatus.OK


@app.route('/not_found/film', methods=['POST'])
@swag.validate('Film', validation_error_handler=validation_error_404)
def create_film_2():
    """
    Film creation endpoint
    ---
    tags:
      - film
    summary: Creates a new Film
    consumes:
      - application/json
    produces:
      - application/json
    parameters:
      - in: body
        name: body
        description:
          Film object that needs to be persisted to the database
        required: true
        schema:
          $ref: '#/definitions/Film'
    responses:
      200:
        description: Successful operation
      400:
        description: Invalid input
    """
    return jsonify(request.json), HTTPStatus.OK


@app.route('/retry/film', methods=['POST'])
@swag.validate('Film', validation_error_handler=validation_error_try_to_accept)
def create_film_3():
    """
    Film creation endpoint
    ---
    tags:
      - film
    summary: Creates a new Film
    consumes:
      - application/json
    produces:
      - application/json
    parameters:
      - in: body
        name: body
        description:
          Film object that needs to be persisted to the database
        required: true
        schema:
          $ref: '#/definitions/Film'
    responses:
      200:
        description: Successful operation
      400:
        description: Invalid input
    """
    return jsonify(request.json), HTTPStatus.OK


def test_swag(client, specs_data):
    """
    This test is runs automatically in Travis CI

    :param client: Flask app test client
    :param specs_data: {'url': {swag_specs}} for every spec in app
    """
    invalid_film = {
        '_id': "594dba7b2879334e411f3dcc",
        'title': "The Last Airbender",
        'director': "M. Night Shyamalan",
        'distributor': "Paramount Pictures",
        'running_time': 103,
        'release_date': "June 30, 2010"
    }

    super_invalid_film = {
        'title': "The Last Airbender",
        'release_date': 2010
    }

    with client.post(
            '/film', data=json.dumps(invalid_film),
            content_type='application/json') as response:
        assert response.status_code == HTTPStatus.BAD_REQUEST

        received = json.loads(response.data.decode('utf-8'))
        assert received.get('error') is not None
        assert received.get('schema') is not None
        assert received.get('data') == invalid_film

    with client.post(
            '/not_found/film', data=json.dumps(invalid_film),
            content_type='application/json') as response:
        assert response.status_code == HTTPStatus.NOT_FOUND

    with client.post(
            '/retry/film', data=json.dumps(invalid_film),
            content_type='application/json') as response:
        assert response.status_code == HTTPStatus.OK

    with client.post(
            '/retry/film', data=json.dumps(super_invalid_film),
            content_type='application/json') as response:
        assert response.status_code == HTTPStatus.BAD_REQUEST

if __name__ == "__main__":
    app.run(debug=True)