Click to jump to the REST-Framework column directory

The View is the code that provides interface services and logic. For example, in Django projects, classes UserLoginViewSet(…) are often defined. Or def user_login(Request, *args, **kwargs), which are view classes or functions defined by the backend service. Register them in the URL object to implement a logical API interface.

APIView

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
from django.views import View


class MedusaView(View) :.Copy the code

If you need to implement a GET request, you implement def GET (self, request, *args,) in your class. If you need to implement a GET request, you implement def GET (self, request, *args,) in your class. **kwargs), of course, POST, DELETE, PUT, etc., as long as you define it in the attempt and return it a Response object. But when we use reST-Framework, we all use APIView’s inherited parent class,

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
from rest_framework.views import APIView

class MedusaViewSet(APIView) :.Copy the code

If you look at the definition of APIView, it is not difficult to find that it also inherits View implementation, but on the basis of View extends many methods (functions), we can define the View when we need to get the data, we need to return the data. Any exceptions are returned as a status code. You can also override the handle_Exception (self, exc) method to customize the error handler response. For example, you can use request.data.get(“params”) to retrieve json request parameters. You can also use request.query_params.get(“params”) to retrieve URL parameters. This is equivalent to request.get.GET (“params”), which is covered in the Request section.

api_view

If you’re used to the function view, you’re also given the way decorators decorate functions:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
from rest_framework.decorators import api_view


@api_view(['GET'])
def medusa_view(request) :.Copy the code

Of course, the author still considers the class view to be more prescriptive.

The sample

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
from rest_framework import views, response, status


class Medusa(views.APIView) :

    def get(self, request, *args, **kwargs) :
        return response.Response({'detail': 'get'}, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs) :
        return response.Response({'detail': 'post'}, status=status.HTTP_201_CREATED)

    def delete(self, request, *args, **kwargs) :
        return response.Response({'detail': 'delete'}, status=status.HTTP_204_NO_CONTENT)

    def put(self, request, *args, **kwargs) :
        return response.Response({'detail': 'put'}, status=status.HTTP_200_OK)

Copy the code