Check that the request payload data is valid json.

By adding `force=True` to request.get_json() the mime type is ignore. If the data is not valid json the method will return a `BadRequestError` we catch that and throw our own error with a clear error message "Invalid JSON supplied in POST data".
If the json is valid return the json data or an empty dict if None is passed in.

This PR improves the error messages if the json is invalid, previously, the error message was "None object type" message which is not very helpful.
This commit is contained in:
Rebecca Law
2019-11-21 15:21:18 +00:00
parent c78a5d8536
commit 5d6886242b
6 changed files with 60 additions and 27 deletions

View File

@@ -6,17 +6,21 @@ from app.schema_validation import validate
from app.utils import get_template_instance
from app.v2.errors import BadRequestError
from app.v2.template import v2_template_blueprint
from app.v2.template.template_schemas import post_template_preview_request, create_post_template_preview_response
from app.v2.template.template_schemas import (
post_template_preview_request,
create_post_template_preview_response
)
from app.v2.utils import get_valid_json
@v2_template_blueprint.route("/<template_id>/preview", methods=['POST'])
def post_template_preview(template_id):
if not request.content_type or request.content_type != 'application/json':
raise BadRequestError(message="Content-Type header is not set to application/json.",
status_code=400)
_data = request.get_json()
if _data is None:
# If the payload is is empty if there is no personalisation in the template.
_data = request.get_data(as_text=True)
if not _data:
_data = {}
else:
_data = get_valid_json()
_data['id'] = template_id