1-5. View component

Posted by LiquidEagle on Sun, 02 Jan 2022 18:57:29 +0100

chart

2 view base classes

APIView

rest_framework.views.APIView

APIView is the base class of all views provided by the REST framework, which inherits from the View parent class of Django.

APIView differs from View in that:

- Passed into the view method is REST framework of`Request`Object, not Django of`HttpRequeset`Object;
- View methods can return REST framework of`Response`Object, the view is set for the response data( render)Format meeting the requirements of the front end;
- whatever`APIException`Exceptions will be captured and processed into appropriate response information;
- In progress dispatch()Before distribution, the request will be subject to identity authentication, permission check and flow control.

Support defined class properties

authentication_classes	  List or Yuanzu, identity authentication class
permissoin_classes		  List or Yuanzu, permission check class
throttle_classes		  List or Yuanzu, flow control class

In APIView, the methods of get(), post() or other request methods are still defined in the conventional class view.

Example:

from rest_framework.views import APIView
from rest_framework.response import Response

# url(r'^students/$', views.StudentsAPIView.as_view()),
class StudentsAPIView(APIView):
  	
    def get(self, request):
        data_list = Student.objects.all()
        serializer = StudentModelSerializer(instance=data_list, many=True)
        return Response(serializer.data)

GenericAPIView generic view class

Inherited from APIVIew, it mainly adds methods for operating serializers and database queries to provide method support for the execution of the following Mixin extension classes. Usually, it can be used with one or more Mixin extension classes.

-queryset = None  # All data
-serializer_class = None # Serialized class
-lookup_field = 'pk'  # Query the fields of a single converter
# Three methods
self.get_queryset()   # Get all data
self.get_serializer()   # Get serialized class
self.get_object()    # Get single

Properties:

serializer_class indicates the serializer used by the view

queryset indicates the data query set used

lookup_field = 'pk' # query the field of a single converter

method:

**get_serializer(self, *args, kwargs)

Returns the serializer object, which is mainly used for the Mixin extension class. If we want to get the serializer object in the view, we can also call this method directly.

Note that when providing the serializer object, this method will supplement the context attribute of the serializer object with three data objects: request, format and view, which can be used when defining the serializer.

- **request** Request object for the current view
- **view** The currently requested class view object
- format The data format expected to be returned by the current request
get_queryset(self)

The query set used by the return view is mainly used for the Mixin extension class. It is the basis for obtaining data from the list view and detail view. The queryset property is returned by default

get_object(self)

The model class data object required to return the detail view is mainly used for the Mixin extension class.

A model class object that can be called to get detailed information in an attempt.

If the model class object accessed in detail does not exist, 404 will be returned.

Write 5 interfaces by inheriting GenericAPIView

##### Write 5 interfaces by inheriting GenericAPIView
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView  # Inherit APIView and write several class properties


from rest_framework.mixins import RetrieveModelMixin,ListModelMixin,CreateModelMixin
class PublishView(GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer


    def get(self, request):
        obj = self.get_queryset()
        ser = self.get_serializer(instance=obj, many=True)
        return Response(data=ser.data)

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)
        # ser.is_valid(raise_exception=True)


class PublishDetailView(GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer
    def get(self, request, pk):
        obj = self.get_object()  # Get a single message according to pk
        ser = PublishSerializer(instance=obj)
        return Response(data=ser.data)

    def put(self, request, pk):
        obj = self.get_object()  # The data does not exist. If instance is None, Ser Save -- > New

        ser = self.get_serializer(data=request.data, instance=obj)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)

    def delete(self, request, pk):
        res = self.get_object().delete()  # Returns a tuple of the number of rows affected
        print(res)  #
        if res[0] >= 1:
            return Response()
        else:
            return Response('The data to be deleted does not exist')

5 view extension classes

effect:

It provides the implementation of the processing flow of several back-end views (deleted, modified and queried data resources). If the views to be written belong to these five kinds, the views can reuse the code by inheriting the corresponding extension classes to reduce the amount of code they write.

These five extension classes need to be matched with the GenericAPIView parent class, because the implementation of the five extension classes needs to call the serializer and database query methods provided by GenericAPIView.

1.ListModelMixin

  1. Provide the list method to quickly implement the list view
  2. Call GenericAPIView to set the result set
  3. Call the serializer set by GenericAPIView

2.CreateModelMixin

  1. Provide the create(request, *args, **kwargs) method to quickly create the view of resources
  2. The actual creation function is completed by the serialized save method
  3. The save method will call the create method of the serializer

3.RetrieveModelMixin

  1. Provide the retrieve(request, *args, **kwargs) method to quickly return an existing data object.

4.UpdateModelMixin

  1. Provide the update(request, *args, **kwargs) method to quickly update an existing data object.
  2. The internal update function calls the save method of the serializer
  3. The save method calls the serializer's update method

5.DestroyModelMixin

  1. The destroy(request, *args, **kwargs) method is provided to quickly delete an existing data object.
  2. delete method of internal model object

9 view subclasses

ListAPIView

inherit

ListModelMixin,
GenericAPIView

method

get

CreateAPIView

inherit

CreateModelMixin,
GenericAPIView

method

post

ListCreateAPIView

inherit

ListModelMixin,
CreateModelMixin,
GenericAPIView

method

get
post

RetrieveAPIView

inherit

RetrieveModelMixin,
GenericAPIView

method

get

UpdateAPIView

inherit

UpdateModelMixin,
GenericAPIView

method

put

DestroyAPIView

inherit

DestroyModelMixin,
GenericAPIView

method

delete

RetrieveUpdateAPIView

inherit

RetrieveModelMixin,
UpdateModelMixin,
GenericAPIView

method

get
put

RetrieveDestroyAPIView

inherit

RetrieveModelMixin,
DestroyModelMixin,
GenericAPIView

method

get
delete

RetrieveUpdateDestroyAPIView

inherit

RetrieveModelMixin,
UpdateModelMixin,
DestroyModelMixin,
GenericAPIView

method

get
put
delete

View set

characteristic

Using the view set ViewSet, you can put a series of logically related actions into one class:

  1. list() provides a set of data
  2. retrieve() provides a single piece of data
  3. create() creates data
  4. update() saves the data
  5. Destroy() delete data
  6. Custom view method
  7. Simple view definition
  8. Simple routing

application

  1. There are many operations that need to be used for a resource
  2. There are many operation databases
  3. Frequent use of serializers

1) ViewSet

It is inherited from APIView, and its function is basically similar to APIView. It provides identity authentication, permission verification, traffic management, etc.

In the ViewSet, there is no action method provided. We need to implement the action method ourselves.

2)GenericViewSet

It inherits from genericapiview and functions similar to genericapiview. It provides get_object,get_queryset and other methods facilitate the development of list view and detail information view.

3)ModelViewSet

It inherits from GenericAPIVIew and includes ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin and DestoryModelMixin.

4)ReadOnlyModelViewSet

It inherits from GenericAPIVIew and includes ListModelMixin and RetrieveModelMixin.

Topics: DRF