Skip to content

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.py
index 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 APIException
from rest_framework.serializers import ValidationError
from 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.py
index 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 settings
from django.utils.decorators import method_decorator
from rest_framework.decorators import action
+from rest_framework.exceptions import APIException, NotFound
from rest_framework.response import Response
from 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_exception
from catalog.api.utils.throttle import OneThousandPerMinute
from 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 = thumbnail
if 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.py
index 517ed8c60..87cca095f 100644
--- a/api/catalog/api/views/image_views.py
+++ b/api/catalog/api/views/image_views.py
@@ -4,6 +4,7 @@ import struct
from django.conf import settings
from django.http.response import FileResponse, HttpResponse
+from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from rest_framework.decorators import action
from 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_exception
from 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.url
if 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.py
index 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_exception
from catalog.api.controllers import search_controller
from catalog.api.models import ContentProvider
from catalog.api.serializers.provider_serializers import ProviderSerializer
-from catalog.api.utils.exceptions import get_api_exception
from catalog.api.utils.pagination import StandardPagination
from catalog.custom_auto_schema import CustomAutoSchema
@@ -99,7 +98,7 @@ class MediaViewSet(ReadOnlyModelViewSet):
self.paginator.page_count = num_pages
self.paginator.result_count = num_results
except 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 = 10
except 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 controller
except 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.identifier
serializer = 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)