Implementation of DRF request and response

Time:2022-1-2
catalogue
  • 1 request and response
    • 1.1 request
    • 1.2 response
  • 2 view
    • 2.1 write interface based on apiview
    • 2.2 interface written based on genericapiview
    • 2.3 interface based on genericapiview and 5 view extension classes
    • 2.4 write 5 interfaces using modelviewset
    • 2.5 source code analysis viewsetmixin
    • 2.6 view class inheriting viewsetmixin

1 request and response

1.1 request

#Request object
# from rest_framework.request import Request
    def __init__(self, request, parsers=None, authenticators=None,
                 negotiator=None, parser_context=None):
        #Encapsulate the request twice, and take the native request as the name of the DRF request object_ Request attribute
        self._request = request
    def __getattr__(self,item):
     return getattr(self._request,item)
#Request object.data:前端以三种编码方式传入的数据,都可以取出来
#Request object..query_params 与Django标准的request.GET相同,只是更换了更正确的名称而已。

1.2 response

#from rest_framework.response import Response
 def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
        
#Data: the data you want to return, dictionary
#Status: the returned status code. The default value is 200,
 -from rest_ Framework import status under this path, it defines all used status codes as constants
#template_ Name the name of the rendered template (self customized template). You don't need to know
#Headers: response header. You can put something in the response header, which is a dictionary
#content_ Type: the encoding format of the response, application / JSON and text / HTML;

#The browser response is in browser format, and the postman response is in JSON format, which is implemented through configuration (default configuration)
#Both postman and browser return JSON format data
#DRF has a default configuration file -- "first find it from the setting of the project. If it cannot be found, use the default configuration file
#For the configuration information of DRF, first find it in your own class -- the setting of the item -- the default setting
 -Local use: valid for a view class
        -Write the following in the view class
        from rest_framework.renderers import JSONRenderer
        renderer_classes=[JSONRenderer,]
    -Global use: global view class. All requests are valid
     -In setting Py add the following
        REST_FRAMEWORK = {
            'DEFAULT_ RENDERER_ Classes': (# default response render class)
                'rest_ framework. renderers. Jsonrenderer ', # JSON renderer
                'rest_ framework. renderers. Browsable API renderer ', # browse API renderer
            )
        }

2 view

#Two view base classes
APIView
GenericAPIView

2.1 write interface based on apiview

#### views.py
from rest_framework.generics import GenericAPIView
from app01.models import Book
from app01.ser import BookSerializer
#Written based on apiview
class BookView(APIView):
    def get(self,request):
        book_list=Book.objects.all()
        book_ser=BookSerializer(book_list,many=True)

        return Response(book_ser.data)
    def post(self,request):
        book_ser = BookSerializer(data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            Return response ({'status': 101,' MSG ':' verification failed '})


class BookDetailView(APIView):
    def get(self, request,pk):
        book = Book.objects.all().filter(pk=pk).first()
        book_ser = BookSerializer(book)
        return Response(book_ser.data)

    def put(self, request,pk):
        book = Book.objects.all().filter(pk=pk).first()
        book_ser = BookSerializer(instance=book,data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            Return response ({'status': 101,' MSG ':' verification failed '})

    def delete(self,request,pk):
        ret=Book.objects.filter(pk=pk).delete()
        Return response ({'status': 100,' MSG ':' deletion succeeded '})
    
#models.py
class Book(models.Model):
    name=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=5,decimal_places=2)
    publish=models.CharField(max_length=32)
#ser.py
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields='__all__'
# urls.py
path('books/', views.BookView.as_view()),
re_path('books/(?P<pk>\d+)', views.BookDetailView.as_view()),

2.2 interface written based on genericapiview

# views.py
class Book2View(GenericAPIView):
    #Queryset passes the queryset object to query all books
    # serializer_ Class uses which serialization class to serialize this pile of data
    queryset=Book.objects
    # queryset=Book.objects.all()
    serializer_class = BookSerializer
    def get(self,request):
        book_list=self.get_queryset()
        book_ser=self.get_serializer(book_list,many=True)

        return Response(book_ser.data)
    def post(self,request):
        book_ser = self.get_serializer(data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            Return response ({'status': 101,' MSG ':' verification failed '})


class Book2DetailView(GenericAPIView):
    queryset = Book.objects
    serializer_class = BookSerializer
    def get(self, request,pk):
        book = self.get_object()
        book_ser = self.get_serializer(book)
        return Response(book_ser.data)

    def put(self, request,pk):
        book = self.get_object()
        book_ser = self.get_serializer(instance=book,data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            Return response ({'status': 101,' MSG ':' verification failed '})

    def delete(self,request,pk):
        ret=self.get_object().delete()
        Return response ({'status': 100,' MSG ':' deletion succeeded '})
    
 #url.py
    #Overridden using genericapiview
    path('books2/', views.Book2View.as_view()),
    re_path('books2/(?P<pk>\d+)', views.Book2DetailView.as_view()),

2.3 interface based on genericapiview and 5 view extension classes

from rest_framework.mixins import  ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
# views.py
class Book3View(GenericAPIView,ListModelMixin,CreateModelMixin):

    queryset=Book.objects
    serializer_class = BookSerializer
    def get(self,request):
        return self.list(request)

    def post(self,request):
        return self.create(request)

class Book3DetailView(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin):
    queryset = Book.objects
    serializer_class = BookSerializer
    def get(self, request,pk):
        return self.retrieve(request,pk)

    def put(self, request,pk):
        return self.update(request,pk)

    def delete(self,request,pk):
        return self.destroy(request,pk)
# urls.py
    #Overridden using genericapiview + 5 view extension classes
    path('books3/', views.Book3View.as_view()),
    re_path('books3/(?P<pk>\d+)', views.Book3DetailView.as_view()),

2.4 write 5 interfaces using modelviewset

# views.py
from rest_framework.viewsets import ModelViewSet
Class book5view (modelviewset): #5 there are all interfaces, but there is a problem with the routing
    queryset = Book.objects
    serializer_class = BookSerializer
    
# urls.py
#Write 5 interfaces using modelviewset
    Path ('books5 / ', views.book5view.as_view (actions = {get':'List ','post':'create '})), # when the path matches and the get request, the list method of book5view will be executed
    re_path('books5/(?P<pk>\d+)', views.Book5View.as_view(actions={'get':'retrieve','put':'update','delete':'destroy'})),

2.5 source code analysis viewsetmixin

#Rewritten as_ view
#Core code (so as long as the corresponding relationship is configured in the route, such as {get ':'List'}), when the get request comes, the list method will be executed
for method, action in actions.items():
    #method:get
    # action:list
    handler = getattr(self, action)
    #After executing the previous sentence, the handler becomes the memory address of the list
    setattr(self, method, handler)
    #Finish executing the object of the previous sentence get=list
    #Object after the for loop is executed Get: the list object Post: create

2.6 view class inheriting viewsetmixin

# views.py
from rest_framework.viewsets import ViewSetMixin
Class book6view (viewsetmixin, apiview): # be sure to put it in front of apiview
    def get_all_book(self,request):
        print("xxxx")
        book_list = Book.objects.all()
        book_ser = BookSerializer(book_list, many=True)
        return Response(book_ser.data)
    
# urls.py
    #Inherit the view class of viewsetmixin, and the route can be rewritten as follows
    path('books6/', views.Book6View.as_view(actions={'get': 'get_all_book'})),

What is a forward proxy and what is a reverse proxy

The object of forward proxy is the client, and the object of reverse proxy is the server

This is the end of this article on the implementation of DRF requests and responses. For more DRF requests and responses, please search for previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!