Skip to content

Commit

Permalink
🐛(back) handle Django ValidationError as an accepted exception
Browse files Browse the repository at this point in the history
When the django model raised a ValidationError, this exception is not
managed by DRF. To fix this issue we have to override the DRF
exception_handler.
The solution was found in this gist :
https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f
  • Loading branch information
lunika committed Feb 4, 2021
1 parent a43402c commit c390a11
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ Versioning](https://semver.org/spec/v2.0.0.html).

- Switch to QVBR rate control mode in live profiles

### Fixed

- Handle Django ValidationError as an accepted exception

### Removed

- Dash endpoint in mediapackage channel
Expand Down
22 changes: 22 additions & 0 deletions src/backend/marsha/core/tests/test_api_thumbnail.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,28 @@ def test_api_thumbnail_create_instructor(self):
},
)

def test_api_thumbnail_create_already_existing_instructor(self):
"""Creating a thumbnail should fail when a thumbnail already exists for the video."""
video = VideoFactory()
ThumbnailFactory(video=video)

jwt_token = AccessToken()
jwt_token.payload["resource_id"] = str(video.id)
jwt_token.payload["roles"] = [random.choice(["instructor", "administrator"])]
jwt_token.payload["permissions"] = {"can_update": True}

response = self.client.post(
"/api/thumbnails/", HTTP_AUTHORIZATION="Bearer {!s}".format(jwt_token)
)

self.assertEqual(response.status_code, 400)
content = json.loads(response.content)

self.assertEqual(
content,
{"video": ["Thumbnail with this Video already exists."]},
)

def test_api_thumbnail_instructor_create_in_read_only(self):
"""Instructor should not be able to create thumbnails in a read_only mode."""
thumbnail = ThumbnailFactory()
Expand Down
27 changes: 26 additions & 1 deletion src/backend/marsha/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import (
ImproperlyConfigured,
ValidationError as DjangoValidationError,
)
from django.templatetags.static import static
from django.utils.decorators import method_decorator
from django.views.decorators.clickjacking import xframe_options_exempt
Expand All @@ -15,6 +18,8 @@
from django.views.generic.base import TemplateResponseMixin, TemplateView

from pylti.common import LTIException
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_simplejwt.tokens import AccessToken
from waffle import switch_is_active

Expand All @@ -30,6 +35,26 @@
logger = getLogger(__name__)


def exception_handler(exc, context):
"""Handle Django ValidationError as an accepted exception.
For the parameters, see ``exception_handler``
This code comes from twidi's gist:
https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f
"""
if isinstance(exc, DjangoValidationError):
if hasattr(exc, "message_dict"):
detail = exc.message_dict
elif hasattr(exc, "message"):
detail = exc.message
elif hasattr(exc, "messages"):
detail = exc.messages

exc = DRFValidationError(detail=detail)

return drf_exception_handler(exc, context)


@method_decorator(csrf_exempt, name="dispatch")
@method_decorator(xframe_options_exempt, name="dispatch")
class BaseView(ABC, TemplateResponseMixin, View):
Expand Down
3 changes: 2 additions & 1 deletion src/backend/marsha/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ class Base(Configuration):
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTTokenUserAuthentication",
)
),
"EXCEPTION_HANDLER": "marsha.core.views.exception_handler",
}

# WAFFLE
Expand Down

0 comments on commit c390a11

Please sign in to comment.