From 21558f1d3c204b17ac01e0737fd06c4ade4638b7 Mon Sep 17 00:00:00 2001 From: Aadesh-Baral Date: Wed, 28 Jun 2023 11:00:17 +0545 Subject: [PATCH] Update decorator to handle invalid/empty json body. ----------------------------------------------- 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. --- backend/models/dtos/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/backend/models/dtos/__init__.py b/backend/models/dtos/__init__.py index 5b52341dbf..61376b35ad 100644 --- a/backend/models/dtos/__init__.py +++ b/backend/models/dtos/__init__.py @@ -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 @@ -32,6 +32,12 @@ 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 @@ -39,8 +45,8 @@ def wrapper(*args, **kwargs): 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: