Skip to content

Commit

Permalink
Update decorator to handle invalid/empty json body.
Browse files Browse the repository at this point in the history
-----------------------------------------------
This commit refactors the request body handling in the validate_request decorator. Previously, the code attempted to access request.json directly, which could raise a "Failed to decode JSON object" error when the request body was empty or contained invalid JSON.

To address this issue, the code has been updated to use a try-except block. It now checks request.is_json and handles two scenarios:

- If request.is_json is True, indicating a JSON content type, it tries to access request.json to retrieve the JSON payload. If the request body contains invalid JSON, the WerkzeugBadRequest exception is caught, and the body is set to an empty dictionary.

- If request.is_json is False or request.json raises an error for any reason, body is also set to an empty dictionary.
  • Loading branch information
Aadesh-Baral committed Jun 28, 2023
1 parent 2a1ab0c commit 21558f1
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions backend/models/dtos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import wraps
from flask import request
from schematics.exceptions import DataError

from werkzeug.exceptions import BadRequest as WerkzeugBadRequest

from backend.exceptions import BadRequest

Expand Down Expand Up @@ -32,15 +32,21 @@ def wrapper(*args, **kwargs):

try:
dto = dto_class()
try:
body = request.json if request.is_json else {}
except (
WerkzeugBadRequest
): # If request body does not contain valid JSON then BadRequest is raised by Flask
body = {}

for attr in dto.__class__._fields:
# Get serialized name of attr if exists otherwise use attr name
field = dto.__class__._fields[attr]
attr_name = field.serialized_name if field.serialized_name else attr

# Set attribute value from request body, query parameters, or path parameters
if request.is_json and attr_name in request.json:
setattr(dto, attr, request.json[attr_name])
if attr_name in body:
setattr(dto, attr, body[attr_name])
elif attr_name in request.args:
setattr(dto, attr, request.args.get(attr_name))
elif attr_name in kwargs:
Expand Down

0 comments on commit 21558f1

Please sign in to comment.