-
Notifications
You must be signed in to change notification settings - Fork 1
/
flask_jsonschema.py
60 lines (52 loc) · 2.1 KB
/
flask_jsonschema.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
"""
Simple JSON Schema validator for Flask.
:copyright: (c) 2015 by William Clemens.
:license: MIT, see LICENSE for more details.
"""
import flask
import functools
import jsonschema
from werkzeug.exceptions import BadRequest
def _json_path_to_string(path):
formated_path = "(root)"
for part in path:
if isinstance(part, int):
formated_path = "{0}[{1}]".format(formated_path, part)
else:
formated_path = "{0}.{1}".format(formated_path, part)
return formated_path
def validate(schema, force=False, json_cache=True):
"""Simple decorator for validating JSON request.
:param schema: python object conforming to JSON schema.
:param force: forces validation if mimetype is not
'application/json'.
:param json_cache: caches parsed JSON object. This is recommend as
if the request body is going to be used in the
request.
"""
def decorator(func):
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
if flask.request.mimetype == 'application/json' or force:
try:
jsonschema.validate(
flask.request.get_json(force=force, cache=json_cache),
schema,
)
except jsonschema.ValidationError as err:
return flask.jsonify(
status=400,
status_message="Bad Request",
error_message=err.message,
error_path=_json_path_to_string(err.absolute_path),
), 400
except BadRequest as err:
return flask.jsonify(
status=err.code,
status_message=err.name,
error_message="Failed to decode request body.",
error_path=None,
), err.code
return func(*args, **kwargs)
return func_wrapper
return decorator