| 1 |
--- |
| 2 |
source: |
| 3 |
- decorators.py |
| 4 |
- views.py |
| 5 |
--- |
| 6 |
|
| 7 |
## Class-based Views |
| 8 |
|
| 9 |
> Django's class-based views are a welcome departure from the old-style views. |
| 10 |
> |
| 11 |
> — [Reinout van Rees][cite] |
| 12 |
|
| 13 |
REST framework provides an `APIView` class, which subclasses Django's `View` class. |
| 14 |
|
| 15 |
`APIView` classes are different from regular `View` classes in the following ways: |
| 16 |
|
| 17 |
* Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances. |
| 18 |
* Handler methods may return REST framework's `Response`, instead of Django's `HttpResponse`. The view will manage content negotiation and setting the correct renderer on the response. |
| 19 |
* Any `APIException` exceptions will be caught and mediated into appropriate responses. |
| 20 |
* Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. |
| 21 |
|
| 22 |
Using the `APIView` class is pretty much the same as using a regular `View` class, as usual, the incoming request is dispatched to an appropriate handler method such as `.get()` or `.post()`. Additionally, a number of attributes may be set on the class that control various aspects of the API policy. |
| 23 |
|
| 24 |
For example: |
| 25 |
|
| 26 |
from rest_framework.views import APIView |
| 27 |
from rest_framework.response import Response |
| 28 |
from rest_framework import authentication, permissions |
| 29 |
from django.contrib.auth.models import User |
| 30 |
|
| 31 |
class ListUsers(APIView): |
| 32 |
""" |
| 33 |
View to list all users in the system. |
| 34 |
|
| 35 |
* Requires token authentication. |
| 36 |
* Only admin users are able to access this view. |
| 37 |
""" |
| 38 |
authentication_classes = [authentication.TokenAuthentication] |
| 39 |
permission_classes = [permissions.IsAdminUser] |
| 40 |
|
| 41 |
def get(self, request, format=None): |
| 42 |
""" |
| 43 |
Return a list of all users. |
| 44 |
""" |
| 45 |
usernames = [user.username for user in User.objects.all()] |
| 46 |
return Response(usernames) |
| 47 |
|
| 48 |
!!! note |
| 49 |
The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views. |
| 50 |
|
| 51 |
|
| 52 |
### API policy attributes |
| 53 |
|
| 54 |
The following attributes control the pluggable aspects of API views. |
| 55 |
|
| 56 |
#### .renderer_classes |
| 57 |
|
| 58 |
#### .parser_classes |
| 59 |
|
| 60 |
#### .authentication_classes |
| 61 |
|
| 62 |
#### .throttle_classes |
| 63 |
|
| 64 |
#### .permission_classes |
| 65 |
|
| 66 |
#### .content_negotiation_class |
| 67 |
|
| 68 |
### API policy instantiation methods |
| 69 |
|
| 70 |
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods. |
| 71 |
|
| 72 |
#### .get_renderers(self) |
| 73 |
|
| 74 |
#### .get_parsers(self) |
| 75 |
|
| 76 |
#### .get_authenticators(self) |
| 77 |
|
| 78 |
#### .get_throttles(self) |
| 79 |
|
| 80 |
#### .get_permissions(self) |
| 81 |
|
| 82 |
#### .get_content_negotiator(self) |
| 83 |
|
| 84 |
#### .get_exception_handler(self) |
| 85 |
|
| 86 |
### API policy implementation methods |
| 87 |
|
| 88 |
The following methods are called before dispatching to the handler method. |
| 89 |
|
| 90 |
#### .check_permissions(self, request) |
| 91 |
|
| 92 |
#### .check_throttles(self, request) |
| 93 |
|
| 94 |
#### .perform_content_negotiation(self, request, force=False) |
| 95 |
|
| 96 |
### Dispatch methods |
| 97 |
|
| 98 |
The following methods are called directly by the view's `.dispatch()` method. |
| 99 |
These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`. |
| 100 |
|
| 101 |
#### .initial(self, request, \*args, **kwargs) |
| 102 |
|
| 103 |
Performs any actions that need to occur before the handler method gets called. |
| 104 |
This method is used to enforce permissions and throttling, and perform content negotiation. |
| 105 |
|
| 106 |
You won't typically need to override this method. |
| 107 |
|
| 108 |
#### .handle_exception(self, exc) |
| 109 |
|
| 110 |
Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception. |
| 111 |
|
| 112 |
The default implementation handles any subclass of `rest_framework.exceptions.APIException`, as well as Django's `Http404` and `PermissionDenied` exceptions, and returns an appropriate error response. |
| 113 |
|
| 114 |
If you need to customize the error responses your API returns you should subclass this method. |
| 115 |
|
| 116 |
#### .initialize_request(self, request, \*args, **kwargs) |
| 117 |
|
| 118 |
Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`. |
| 119 |
|
| 120 |
You won't typically need to override this method. |
| 121 |
|
| 122 |
#### .finalize_response(self, request, response, \*args, **kwargs) |
| 123 |
|
| 124 |
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. |
| 125 |
|
| 126 |
You won't typically need to override this method. |
| 127 |
|
| 128 |
--- |
| 129 |
|
| 130 |
## Function Based Views |
| 131 |
|
| 132 |
> Saying [that class-based views] is always the superior solution is a mistake. |
| 133 |
> |
| 134 |
> — [Nick Coghlan][cite2] |
| 135 |
|
| 136 |
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. |
| 137 |
|
| 138 |
### @api_view() |
| 139 |
|
| 140 |
**Signature:** `@api_view(http_method_names=['GET'])` |
| 141 |
|
| 142 |
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: |
| 143 |
|
| 144 |
from rest_framework.decorators import api_view |
| 145 |
from rest_framework.response import Response |
| 146 |
|
| 147 |
@api_view() |
| 148 |
def hello_world(request): |
| 149 |
return Response({"message": "Hello, world!"}) |
| 150 |
|
| 151 |
This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. |
| 152 |
|
| 153 |
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: |
| 154 |
|
| 155 |
@api_view(['GET', 'POST']) |
| 156 |
def hello_world(request): |
| 157 |
if request.method == 'POST': |
| 158 |
return Response({"message": "Got some data!", "data": request.data}) |
| 159 |
return Response({"message": "Hello, world!"}) |
| 160 |
|
| 161 |
|
| 162 |
### API policy decorators |
| 163 |
|
| 164 |
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: |
| 165 |
|
| 166 |
from rest_framework.decorators import api_view, throttle_classes |
| 167 |
from rest_framework.throttling import UserRateThrottle |
| 168 |
|
| 169 |
class OncePerDayUserThrottle(UserRateThrottle): |
| 170 |
rate = '1/day' |
| 171 |
|
| 172 |
@api_view(['GET']) |
| 173 |
@throttle_classes([OncePerDayUserThrottle]) |
| 174 |
def view(request): |
| 175 |
return Response({"message": "Hello for today! See you tomorrow!"}) |
| 176 |
|
| 177 |
These decorators correspond to the attributes set on `APIView` subclasses, described above. |
| 178 |
|
| 179 |
The available decorators are: |
| 180 |
|
| 181 |
* `@renderer_classes(...)` |
| 182 |
* `@parser_classes(...)` |
| 183 |
* `@authentication_classes(...)` |
| 184 |
* `@throttle_classes(...)` |
| 185 |
* `@permission_classes(...)` |
| 186 |
* `@content_negotiation_class(...)` |
| 187 |
* `@metadata_class(...)` |
| 188 |
* `@versioning_class(...)` |
| 189 |
|
| 190 |
Each of these decorators is equivalent to setting their respective [api policy attributes][api-policy-attributes]. |
| 191 |
|
| 192 |
All decorators take a single argument. The ones that end with `_class` expect a single class while the ones ending in `_classes` expect a list or tuple of classes. |
| 193 |
|
| 194 |
|
| 195 |
### View schema decorator |
| 196 |
|
| 197 |
To override the default schema generation for function based views you may use |
| 198 |
the `@schema` decorator. This must come *after* (below) the `@api_view` |
| 199 |
decorator. For example: |
| 200 |
|
| 201 |
from rest_framework.decorators import api_view, schema |
| 202 |
from rest_framework.schemas import AutoSchema |
| 203 |
|
| 204 |
class CustomAutoSchema(AutoSchema): |
| 205 |
def get_operation(self, path, method): |
| 206 |
# override view introspection here... |
| 207 |
|
| 208 |
@api_view(['GET']) |
| 209 |
@schema(CustomAutoSchema()) |
| 210 |
def view(request): |
| 211 |
return Response({"message": "Hello for today! See you tomorrow!"}) |
| 212 |
|
| 213 |
This decorator takes a single `AutoSchema` instance or an `AutoSchema` subclass |
| 214 |
instance as described in the [Schemas documentation][schemas]. |
| 215 |
You may pass `None` in order to exclude the view from schema generation. |
| 216 |
|
| 217 |
@api_view(['GET']) |
| 218 |
@schema(None) |
| 219 |
def view(request): |
| 220 |
return Response({"message": "Will not appear in schema!"}) |
| 221 |
|
| 222 |
### Throttle scope decorator |
| 223 |
|
| 224 |
To set the throttle scope of function based views you may use the `@throttle_scope` decorator: |
| 225 |
|
| 226 |
from rest_framework.decorators import api_view, throttle_scope |
| 227 |
|
| 228 |
@api_view(['GET']) |
| 229 |
@throttle_scope("hello") |
| 230 |
def view(request): |
| 231 |
return Response({"message": "Hello for today! See you tomorrow!"}) |
| 232 |
|
| 233 |
See [ScopedRateThrottle documentation][scoped-rate-throttle] for more details. |
| 234 |
|
| 235 |
|
| 236 |
[cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html |
| 237 |
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html |
| 238 |
[settings]: settings.md |
| 239 |
[throttling]: throttling.md |
| 240 |
[schemas]: schemas.md |
| 241 |
[scoped-rate-throttle]: throttling.md#scopedratethrottle |
| 242 |
[classy-drf]: http://www.cdrf.co |
| 243 |
[api-policy-attributes]: views.md#api-policy-attributes |
| 244 |
|