CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-djangorestframework

Web APIs for Django, made easy.

Pending
Overview
Eval results
Files

decorators.mddocs/

Decorators and Function-Based Views

Essential decorators for function-based views and ViewSet customization in Django REST Framework. These decorators enable the creation of API views from regular functions and provide flexible configuration options for policies and routing.

Core Imports

from rest_framework.decorators import (
    api_view, action, permission_classes, authentication_classes, 
    throttle_classes, parser_classes, renderer_classes, schema
)

Capabilities

Function-Based View Decorator

The @api_view decorator converts regular Django functions into REST framework APIView subclasses with full DRF functionality.

def api_view(http_method_names=None):
    """
    Decorator that converts a function-based view into an APIView subclass.
    
    Parameters:
    - http_method_names (list): Allowed HTTP methods for the view (defaults to ['GET'])
    
    Returns:
    Function that returns an APIView.as_view() instance
    """

Usage example:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

@api_view(['GET', 'POST'])
def user_list(request):
    if request.method == 'GET':
        # Handle GET request
        return Response({'users': []})
    elif request.method == 'POST':
        # Handle POST request
        return Response({'message': 'User created'}, status=status.HTTP_201_CREATED)

ViewSet Action Decorator

The @action decorator marks ViewSet methods as routable actions, creating custom endpoints beyond the standard CRUD operations.

def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
    """
    Mark a ViewSet method as a routable action.
    
    Parameters:
    - methods (list): HTTP method names this action responds to (defaults to ['get'])
    - detail (bool): Required. True for instance actions, False for collection actions
    - url_path (str): URL segment for this action (defaults to method name)
    - url_name (str): Internal URL name for reversing (defaults to method name with dashes)
    - **kwargs: Additional properties to override viewset-level settings
    
    Returns:
    Decorated method with routing metadata
    """

Usage examples:

from rest_framework.decorators import action
from rest_framework.response import Response

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    
    @action(detail=True, methods=['post'])
    def set_favorite(self, request, pk=None):
        book = self.get_object()
        # Custom action logic
        return Response({'status': 'favorite set'})
    
    @action(detail=False)
    def recent_books(self, request):
        recent = Book.objects.filter(created__gte=last_week)
        # Collection action logic
        return Response(BookSerializer(recent, many=True).data)

Policy Configuration Decorators

These decorators set specific policy classes for function-based views, overriding default API settings.

def permission_classes(permission_classes):
    """
    Set permission classes for function-based views.
    
    Parameters:
    - permission_classes (list): List of permission class objects
    """

def authentication_classes(authentication_classes):
    """
    Set authentication classes for function-based views.
    
    Parameters:
    - authentication_classes (list): List of authentication class objects
    """

def throttle_classes(throttle_classes):
    """
    Set throttle classes for function-based views.
    
    Parameters:
    - throttle_classes (list): List of throttle class objects
    """

def parser_classes(parser_classes):
    """
    Set parser classes for function-based views.
    
    Parameters:
    - parser_classes (list): List of parser class objects
    """

def renderer_classes(renderer_classes):
    """
    Set renderer classes for function-based views.
    
    Parameters:
    - renderer_classes (list): List of renderer class objects
    """

def schema(view_inspector):
    """
    Set schema inspector for function-based views.
    
    Parameters:
    - view_inspector: Schema inspector class or instance
    """

Usage example:

from rest_framework.decorators import (
    api_view, permission_classes, authentication_classes, throttle_classes
)
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from rest_framework.throttling import UserRateThrottle

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
@authentication_classes([TokenAuthentication])
@throttle_classes([UserRateThrottle])
def protected_view(request):
    return Response({'message': 'Authenticated and throttled endpoint'})

Method Mapping for Actions

The MethodMapper class enables mapping different HTTP methods to separate ViewSet methods for a single logical action.

class MethodMapper(dict):
    """
    Enables mapping HTTP methods to different ViewSet methods for a single,
    logical action.
    
    Methods:
    - get(func): Map GET method to function
    - post(func): Map POST method to function  
    - put(func): Map PUT method to function
    - patch(func): Map PATCH method to function
    - delete(func): Map DELETE method to function
    - head(func): Map HEAD method to function
    - options(func): Map OPTIONS method to function
    - trace(func): Map TRACE method to function
    """

Usage example:

class BookViewSet(viewsets.ModelViewSet):
    
    @action(detail=False, methods=['get', 'post'])
    def favorites(self, request):
        # Handle GET requests to /books/favorites/
        return Response({'favorites': []})
    
    @favorites.mapping.post
    def create_favorite(self, request):
        # Handle POST requests to /books/favorites/
        return Response({'message': 'Favorite created'})

Types

# Method name constants for decorators
HTTP_METHOD_NAMES = [
    'get', 'post', 'put', 'patch', 'delete', 
    'head', 'options', 'trace'
]

# Decorator function type
DecoratorFunc = Callable[[Callable], Callable]

Install with Tessl CLI

npx tessl i tessl/pypi-djangorestframework

docs

auth-permissions.md

content-negotiation.md

decorators.md

fields-validation.md

generic-views.md

index.md

pagination-filtering.md

request-response.md

routers-urls.md

serializers.md

status-exceptions.md

testing.md

views-viewsets.md

tile.json