edX DRF Extensions

10.6.0 · active · verified Fri Apr 17

edX DRF Extensions provides a collection of utility classes, authenticators, permissions, and exception handlers designed to extend Django REST Framework for use within the Open edX ecosystem. It is currently at version 10.6.0, with a frequent release cadence tied to Django and Python version compatibility and Open edX platform development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to apply `JwtCookieAuthentication` to a Django REST Framework ViewSet, allowing JWT-based authentication via cookies. It also shows how the `exception_handler` can be used (typically configured in `settings.py`) to provide consistent error responses. The `cause_handled_error` action simulates an exception that would be processed by the custom handler.

import os
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.http import Http404

# Ensure these imports are correct for your installed version
from edx_drf_extensions.auth.jwt.authentication import JwtCookieAuthentication
from edx_drf_extensions.exception_handler import exception_handler

# In a Django settings.py file, you'd typically configure DRF:
# REST_FRAMEWORK = {
#     'DEFAULT_AUTHENTICATION_CLASSES': [
#         'edx_drf_extensions.auth.jwt.authentication.JwtCookieAuthentication',
#         'rest_framework.authentication.SessionAuthentication',
#     ],
#     'EXCEPTION_HANDLER': 'edx_drf_extensions.exception_handler.exception_handler'
# }

class MyTestViewSet(viewsets.ViewSet):
    """A simple DRF view demonstrating edx-drf-extensions authentication."""
    authentication_classes = [JwtCookieAuthentication]
    # Permission classes would typically be added here, e.g., IsAuthenticated

    def list(self, request):
        if request.user.is_authenticated:
            return Response({"message": f"Hello {request.user.username}, authenticated via JWT!"}, status=status.HTTP_200_OK)
        return Response({"message": "Authentication failed."},
                        status=status.HTTP_401_UNAUTHORIZED)

    @action(detail=False, methods=['get'])
    def cause_handled_error(self, request):
        """Endpoint to demonstrate the custom exception handler."""
        # This error will be caught by DRF's exception handling, if configured.
        raise Http404("The requested resource was not found. (Handled by edx-drf-extensions)")

print("Quickstart code demonstrates applying JwtCookieAuthentication to a DRF ViewSet.")
print("It also hints at configuring the custom exception_handler in settings.py.")
print("To run fully, integrate into a Django/DRF project and configure REST_FRAMEWORK.")

view raw JSON →