Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Removed get_api_exception and replaced it with appropriate built-in DRF Exceptions (#976)
Abhishek Yadav0c1dcddc171a
diff --git a/api/catalog/api/utils/exceptions.py b/api/catalog/api/utils/exceptions.pyindex fb3f99c6e..4fd7e7058 100644--- a/api/catalog/api/utils/exceptions.py+++ b/api/catalog/api/utils/exceptions.py@@ -1,29 +1,7 @@-from rest_framework.exceptions import APIExceptionfrom rest_framework.serializers import ValidationErrorfrom rest_framework.views import exception_handler as drf_exception_handler-def get_api_exception(error_message, response_code=500, error_code=None):- """- Returns an instance of a subclass of ``APIException`` with the given error- message, error code and response status code.-- The returned object should be used with the ``raise`` keyword.-- :param error_message: the detailed error message shown to the user- :param response_code: the HTTP response status code- :param error_code: the codename of the error- :return: an instance of a subclass of ``APIException``- """-- class SubAPIException(APIException):- status_code = response_code- default_detail = error_message- default_code = error_code-- return SubAPIException()--def exception_handler(ex, context):"""Handle the exception raised in a DRF context. See `DRF docs`_.diff --git a/api/catalog/api/views/audio_views.py b/api/catalog/api/views/audio_views.pyindex a22cd1bec..ca4748c56 100644--- a/api/catalog/api/views/audio_views.py+++ b/api/catalog/api/views/audio_views.py@@ -1,6 +1,7 @@from django.conf import settingsfrom django.utils.decorators import method_decoratorfrom rest_framework.decorators import action+from rest_framework.exceptions import APIException, NotFoundfrom rest_framework.response import Responsefrom drf_yasg.utils import swagger_auto_schema@@ -22,7 +23,6 @@ from catalog.api.serializers.audio_serializers import (AudioWaveformSerializer,)from catalog.api.serializers.media_serializers import MediaThumbnailRequestSerializer-from catalog.api.utils.exceptions import get_api_exceptionfrom catalog.api.utils.throttle import OneThousandPerMinutefrom catalog.api.views.media_views import MediaViewSet@@ -64,7 +64,7 @@ class AudioViewSet(MediaViewSet):elif audio.audio_set and (thumbnail := audio.audio_set.thumbnail):image_url = thumbnailif not image_url:- raise get_api_exception("Could not find artwork.", 404)+ raise NotFound("Could not find artwork.")return super().thumbnail(image_url, request)@@ -82,7 +82,7 @@ class AudioViewSet(MediaViewSet):return Response(status=200, data=serializer.data)except Exception as e:- raise get_api_exception(getattr(e, "message", str(e)))+ raise APIException(getattr(e, "message", str(e)))@action(detail=True,diff --git a/api/catalog/api/views/image_views.py b/api/catalog/api/views/image_views.pyindex 517ed8c60..87cca095f 100644--- a/api/catalog/api/views/image_views.py+++ b/api/catalog/api/views/image_views.py@@ -4,6 +4,7 @@ import structfrom django.conf import settingsfrom django.http.response import FileResponse, HttpResponse+from django.shortcuts import get_object_or_404from django.utils.decorators import method_decoratorfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound@@ -34,7 +35,6 @@ from catalog.api.serializers.image_serializers import (WatermarkRequestSerializer,)from catalog.api.serializers.media_serializers import MediaThumbnailRequestSerializer-from catalog.api.utils.exceptions import get_api_exceptionfrom catalog.api.utils.throttle import (AnonThumbnailRateThrottle,OAuth2IdThumbnailRateThrottle,@@ -85,10 +85,7 @@ class ImageViewSet(MediaViewSet):if url.endswith("/"):url = url[:-1]identifier = url.rsplit("/", 1)[1]- try:- image = self.get_queryset().get(identifier=identifier)- except Image.DoesNotExist:- raise get_api_exception("Could not find image.", 404)+ image = get_object_or_404(Image, identifier=identifier)if not (image.height and image.width):image_file = requests.get(image.url, headers=self.OEMBED_HEADERS)width, height = PILImage.open(io.BytesIO(image_file.content)).size@@ -112,7 +109,7 @@ class ImageViewSet(MediaViewSet):image_url = image.urlif not image_url:- raise get_api_exception("Could not find image.", 404)+ raise NotFound("Could not find image.", 404)# Hotfix to use scaled down version of the image from SMK# TODO Remove when this issue is addressed:diff --git a/api/catalog/api/views/media_views.py b/api/catalog/api/views/media_views.pyindex cfcd15b04..bf21fb965 100644--- a/api/catalog/api/views/media_views.py+++ b/api/catalog/api/views/media_views.py@@ -15,7 +15,6 @@ from sentry_sdk import capture_exceptionfrom catalog.api.controllers import search_controllerfrom catalog.api.models import ContentProviderfrom catalog.api.serializers.provider_serializers import ProviderSerializer-from catalog.api.utils.exceptions import get_api_exceptionfrom catalog.api.utils.pagination import StandardPaginationfrom catalog.custom_auto_schema import CustomAutoSchema@@ -99,7 +98,7 @@ class MediaViewSet(ReadOnlyModelViewSet):self.paginator.page_count = num_pagesself.paginator.result_count = num_resultsexcept ValueError as e:- raise get_api_exception(getattr(e, "message", str(e)))+ raise APIException(getattr(e, "message", str(e)))serializer = self.get_serializer(results, many=True)return self.get_paginated_response(serializer.data)@@ -133,10 +132,10 @@ class MediaViewSet(ReadOnlyModelViewSet):# `page_size` refers to the maximum number of related images to return.self.paginator.page_size = 10except ValueError as e:- raise get_api_exception(getattr(e, "message", str(e)))+ raise APIException(getattr(e, "message", str(e)))# If there are no hits in the search controllerexcept IndexError:- raise get_api_exception("Could not find items.", 404)+ raise APIException("Could not find items.", 404)serializer = self.get_serializer(results, many=True)return self.get_paginated_response(serializer.data)@@ -145,8 +144,7 @@ class MediaViewSet(ReadOnlyModelViewSet):media = self.get_object()identifier = media.identifierserializer = self.get_serializer(data=request.data)- if not serializer.is_valid():- raise get_api_exception("Invalid input.", 400)+ serializer.is_valid(raise_exception=True)report = serializer.save(identifier=identifier)serializer = self.get_serializer(report)