-
Notifications
You must be signed in to change notification settings - Fork 26
Better JSON handling in requests and responses #45
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,7 +12,7 @@ | |
else: | ||
from io import BytesIO as IO | ||
import numpy as np | ||
from flask import after_this_request, request | ||
from flask import after_this_request, request, jsonify | ||
|
||
|
||
URL_REGEX = re.compile( | ||
|
@@ -23,6 +23,19 @@ | |
r'(?::\d+)?' # optional port | ||
r'(?:/?|[/?]\S+)$', re.IGNORECASE) | ||
|
||
def validate_post_request_body_is_json(f): | ||
@functools.wraps(f) | ||
def wrapped(*args, **kwargs): | ||
json = get_json_or_none_if_invalid(request) | ||
if json is not None: | ||
return f(*args, **kwargs) | ||
else: | ||
err_msg = 'The body of all POST requests must contain JSON' | ||
return jsonify(dict(error=err_msg)), 400 | ||
return wrapped | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A decorator to wrap around |
||
|
||
def get_json_or_none_if_invalid(request): | ||
return request.get_json(force=True, silent=True) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a thin wrapper around Flask's We can then use this util function elsewhere to make sure that we are parsing JSON from Flask response objects in a consistent way. |
||
|
||
def serialize_command(cmd): | ||
ret = {} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Flask's
jsonify()
is a helpful replacement forjson.dumps()
that wraps its parameter in a FlaskResponse
object and sets the MIME type toapplication/json
.