class-based views
The Django ' s class-based views is a welcome departure from the Old-style.
-Reinout van Rees
The rest framework provides a APIView class that which subclasses Django ' s View class.
APIViewA class differs View from a normal class in the following ways:
- The requests passed to the handler methods will be an
Request instance of the rest framework, not a Django HttpRequest instance.
- Handler methods may return
Response to the rest frame instead of Django HttpResponse . The view manages the content negotiation and sets the correct renderer based on the response.
- Any
APIException exceptions will be captured and reconciled to the appropriate response.
- Before the request is sent to the handler method, the incoming request is authenticated and the appropriate permission and/or throttle checks is run.
Using APIView classes like regular View classes, as usual, incoming requests are dispatched to the appropriate handler method, such as .get() or. .post() In addition, many properties can be set on classes that control various aspects of the API policy.
For example:
From rest_framework.views import apiviewfrom rest_framework.response import responsefrom rest_framework Import Authentication, Permissionsclass ListUsers (Apiview): "" "View to list all users in the system. * Requires token authentication. * Only Admin users is able to access the this view. "" Authentication_classes = (authentication. Tokenauthentication,) permission_classes = (permissions. Isadminuser,) def get (self, request, Format=none): "" " Return a list of all users. " " usernames = [user.username for user in User.objects.all ()] # list parsing returns all user names return Response (usernames)
Properties of the API policy
The following properties control the pluggable aspects of the API view.
. Renderer_classes.parser_classes.authentication_classes.throttle_classes.permission_classes.content_ An instantiation method of NEGOTIATION_CLASSAPI policy
The rest framework uses the following methods to instantiate various pluggable API policies. you typically do not need to overwrite these methods .
. Get_renderers (self). Get_parsers (self). Get_authenticators (self). Get_throttles (self). Get_permissions (self). Get_content_negotiator (self). Get_exception_handler (self)How API policies are implemented
Call the following methods before dispatching to the handler method.
. Check_permissions (Self,request). Check_throttles (Self,request). perform_content_negotiation (Self,request,force = False) Scheduling mode
The following methods are called .dispatch() directly by the method of the view. These methods perform any actions that need to .get() .post() put() patch() .delete() occur before or after the handler methods call, and so on.
. Initial (self,request,* args,** Kwargs)
Perform any action that needs to occur before calling the handler method. This method is used to execute permissions and restrictions, and to perform content negotiation.
Typically, you do not need to override this method.
. Handle_exception (SELF,EXC)
Any exceptions thrown by the handler method are passed to this method, which returns an instance, Response or throws an exception again.
The default implementation handles any rest_framework.exceptions.APIException subclasses, as well as Django Http404 and PermissionDenied exceptions, and returns the appropriate error response.
If you need to return the error response from the custom API, you should subclass this method.
. Initialize_request (self,request,* args,** Kwargs)
Make sure that the request object passed to the handler method is an Request instance of, not the usual Django HttpRequest .
Typically, you do not need to override this method.
. Finalize_response (self,request,response,* args,** Kwargs)
Ensure that any object returned from the handler method Response is rendered as the correct content type as determined by the contents negotiation.
Typically, you do not need to override this method.
Function Based views
CBV is not always the best solution.
-Nick Caugland
The rest framework also allows the use of regular FBV. It provides a simple set of FBV-bound adorners to ensure that they receive an Request instance (rather than a typical Django HttpRequest instance) and allows them to return Response (not Django HttpResponse ), and also allows you to configure how the request is handled.
@api_view ()
Signature:@api_view(http_method_names=[‘GET‘], exclude_from_schema=False)
The centerpiece of this feature api_view is the adorner, which provides a series of HTTP methods that the view should respond to. For example, this is how to write a very simple view that can only manually return some data:
From rest_framework.decorators import Api_view@api_view () def hello_world (request): return Response ({"Message": " Hello, world! "})
This view will use the default renderers, parsers, authentication classes, etc. specified in Settings
By default, only methods are accepted GET . Other methods will respond with "405 Method not allowed". To change this behavior, specify the methods that the view allows, as follows:
@api_view ([' GET ', ' Post ']) def hello_world (request): if Request.method = = ' Post ': return Response ({"Message": "Got some data!", "Data": Request.data}) return Response ({"Message": "Hello, world!"})
You can also mark a API view as being omitted from any auto-generated schema, using the exclude_from_schema argument.:
@api_view ([' GET '], exclude_from_schema=true) def api_docs (request): ...
API Policy Adorner
To override the default settings, the rest framework provides a set of other adorners that you can add to the view. These adorners must be placed @api_view underneath the adorner. For example, to use throttle to create a view that can be called only once per day by @throttle_classes A specific user, use the adorner, passing a list of throttle classes:
From rest_framework.decorators import Api_view, throttle_classesfrom rest_framework.throttling Import Userratethrottleclass Onceperdayuserthrottle (userratethrottle): rate = ' 1/day ' @api_view ([' GET ']) @throttle_ Classes ([Onceperdayuserthrottle]) def view (Request): return Response ({"Message": "Hello for today! See you tomorrow! "})
These adorners correspond to the properties set on the APIView subclass described above.
The available adorners are:
@renderer_classes(...)
@parser_classes(...)
@authentication_classes(...)
@throttle_classes(...)
@permission_classes(...)
Each of these adorners requires a parameter, which must be a list or tuple element.
API Guide (iii) views