0
# Decorators and Function-Based Views
1
2
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.
3
4
## Core Imports
5
6
```python
7
from rest_framework.decorators import (
8
api_view, action, permission_classes, authentication_classes,
9
throttle_classes, parser_classes, renderer_classes, schema
10
)
11
```
12
13
## Capabilities
14
15
### Function-Based View Decorator
16
17
The `@api_view` decorator converts regular Django functions into REST framework APIView subclasses with full DRF functionality.
18
19
```python { .api }
20
def api_view(http_method_names=None):
21
"""
22
Decorator that converts a function-based view into an APIView subclass.
23
24
Parameters:
25
- http_method_names (list): Allowed HTTP methods for the view (defaults to ['GET'])
26
27
Returns:
28
Function that returns an APIView.as_view() instance
29
"""
30
```
31
32
Usage example:
33
34
```python
35
from rest_framework.decorators import api_view
36
from rest_framework.response import Response
37
from rest_framework import status
38
39
@api_view(['GET', 'POST'])
40
def user_list(request):
41
if request.method == 'GET':
42
# Handle GET request
43
return Response({'users': []})
44
elif request.method == 'POST':
45
# Handle POST request
46
return Response({'message': 'User created'}, status=status.HTTP_201_CREATED)
47
```
48
49
### ViewSet Action Decorator
50
51
The `@action` decorator marks ViewSet methods as routable actions, creating custom endpoints beyond the standard CRUD operations.
52
53
```python { .api }
54
def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
55
"""
56
Mark a ViewSet method as a routable action.
57
58
Parameters:
59
- methods (list): HTTP method names this action responds to (defaults to ['get'])
60
- detail (bool): Required. True for instance actions, False for collection actions
61
- url_path (str): URL segment for this action (defaults to method name)
62
- url_name (str): Internal URL name for reversing (defaults to method name with dashes)
63
- **kwargs: Additional properties to override viewset-level settings
64
65
Returns:
66
Decorated method with routing metadata
67
"""
68
```
69
70
Usage examples:
71
72
```python
73
from rest_framework.decorators import action
74
from rest_framework.response import Response
75
76
class BookViewSet(viewsets.ModelViewSet):
77
queryset = Book.objects.all()
78
serializer_class = BookSerializer
79
80
@action(detail=True, methods=['post'])
81
def set_favorite(self, request, pk=None):
82
book = self.get_object()
83
# Custom action logic
84
return Response({'status': 'favorite set'})
85
86
@action(detail=False)
87
def recent_books(self, request):
88
recent = Book.objects.filter(created__gte=last_week)
89
# Collection action logic
90
return Response(BookSerializer(recent, many=True).data)
91
```
92
93
### Policy Configuration Decorators
94
95
These decorators set specific policy classes for function-based views, overriding default API settings.
96
97
```python { .api }
98
def permission_classes(permission_classes):
99
"""
100
Set permission classes for function-based views.
101
102
Parameters:
103
- permission_classes (list): List of permission class objects
104
"""
105
106
def authentication_classes(authentication_classes):
107
"""
108
Set authentication classes for function-based views.
109
110
Parameters:
111
- authentication_classes (list): List of authentication class objects
112
"""
113
114
def throttle_classes(throttle_classes):
115
"""
116
Set throttle classes for function-based views.
117
118
Parameters:
119
- throttle_classes (list): List of throttle class objects
120
"""
121
122
def parser_classes(parser_classes):
123
"""
124
Set parser classes for function-based views.
125
126
Parameters:
127
- parser_classes (list): List of parser class objects
128
"""
129
130
def renderer_classes(renderer_classes):
131
"""
132
Set renderer classes for function-based views.
133
134
Parameters:
135
- renderer_classes (list): List of renderer class objects
136
"""
137
138
def schema(view_inspector):
139
"""
140
Set schema inspector for function-based views.
141
142
Parameters:
143
- view_inspector: Schema inspector class or instance
144
"""
145
```
146
147
Usage example:
148
149
```python
150
from rest_framework.decorators import (
151
api_view, permission_classes, authentication_classes, throttle_classes
152
)
153
from rest_framework.permissions import IsAuthenticated
154
from rest_framework.authentication import TokenAuthentication
155
from rest_framework.throttling import UserRateThrottle
156
157
@api_view(['GET', 'POST'])
158
@permission_classes([IsAuthenticated])
159
@authentication_classes([TokenAuthentication])
160
@throttle_classes([UserRateThrottle])
161
def protected_view(request):
162
return Response({'message': 'Authenticated and throttled endpoint'})
163
```
164
165
### Method Mapping for Actions
166
167
The `MethodMapper` class enables mapping different HTTP methods to separate ViewSet methods for a single logical action.
168
169
```python { .api }
170
class MethodMapper(dict):
171
"""
172
Enables mapping HTTP methods to different ViewSet methods for a single,
173
logical action.
174
175
Methods:
176
- get(func): Map GET method to function
177
- post(func): Map POST method to function
178
- put(func): Map PUT method to function
179
- patch(func): Map PATCH method to function
180
- delete(func): Map DELETE method to function
181
- head(func): Map HEAD method to function
182
- options(func): Map OPTIONS method to function
183
- trace(func): Map TRACE method to function
184
"""
185
```
186
187
Usage example:
188
189
```python
190
class BookViewSet(viewsets.ModelViewSet):
191
192
@action(detail=False, methods=['get', 'post'])
193
def favorites(self, request):
194
# Handle GET requests to /books/favorites/
195
return Response({'favorites': []})
196
197
@favorites.mapping.post
198
def create_favorite(self, request):
199
# Handle POST requests to /books/favorites/
200
return Response({'message': 'Favorite created'})
201
```
202
203
## Types
204
205
```python { .api }
206
# Method name constants for decorators
207
HTTP_METHOD_NAMES = [
208
'get', 'post', 'put', 'patch', 'delete',
209
'head', 'options', 'trace'
210
]
211
212
# Decorator function type
213
DecoratorFunc = Callable[[Callable], Callable]
214
```