drf profile view, a view tool, the view set

First, the parameters passed to the view class class sequence

# 1) in the view class instantiation serialized object, context may be provided the content 
# 2) a partial sequence of the hook class, global hook, create, update process, can be passed over with a view class access self.context Content


# Requirements: 
# 1) in the view class, can be obtained by the login user request.user Request 
# 2) in the sequence of the class to complete the verify operation and the database data storage, may be required to know the current login user, but the sequence of categories can not access request 
# . 3) when a serialized object is instantiated, the object passed in the request in the view class

View layer: views.py

class Book(APIView):
    def post(self, request, *args, **kwargs):
        book_ser = serializers.BookModelSerializer(data=request_data,context={'request':request})
        book_ser.is_valid(raise_exception=True)
        book_result = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.BookModelSerializer(book_result).data
        })

Layer sequence: serializers.py

class BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price')
    def validate_name(self, value):
        print(self.context.get('request').method)
        return value

 

Second, the second package type Rseponse

"""
Response({
    'status': 0,
    'msg': 'ok',
    'results': [],
    'Token': '' # such additional key-value data results
},status=http_status,headers=headers,exception=True|False)

APIResponse() => Response({'status': 0,'msg': 'ok'})
"""

from rest_framework.response import Response

class APIResponse (the Response):
     DEF  the __init__ (Self, data_status = 0, data_msg = ' OK ' , Results = None, HTTP_STATUS = None, headers = None, Exception = False, ** kwargs):
         # initial state of the data: status code status information 
        Data = {
             ' status ' : data_status,
             ' MSG ' : data_msg,
        }
        # In response to the data volume data 
        # Results may be False, 0 data, the data will be returned in some cases as valid data 
        IF Results IS  Not None:
            data [ ' Results ' ] = Results
         # additional content data in response to the 
        # IF kwargs None Not IS: 
        #      for K, V in kwargs.items (): 
        #          setattr (data, K, V) 
        data.update (kwargs)

        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

 

Third, view the family

1, views: View

2, generics: View tool

3, mixins: View tool and

4, viewsets: View set

APIView = "GenericAPIView =" mixins = five tools "in the tool view generics =" view of the set viewsets

 

1 "GenericAPIView base class

# GenericAPIView inherited APIView using fully compatible APIView 
# Key: GenericAPIView done what things APIView basis 
# 1) get_queryset (): obtain a model from the class properties queryset in queryset data 
# 2) get_object (): from the class attribute queryset queryset obtained data model, and then the operation target is determined uniquely by the known packet PK 
# . 3) get_serializer (): serializer sequence obtained from the class of the class properties serializer_class

Routing layer

urlpatterns = [
    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),
]

View layer

from rest_framework.generics import GenericAPIView
class BookGenericAPIView(GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer
    # 自定义主键的 有名分组 名
    lookup_field = 'pk'
    # 群取
    # def get(self, request, *args, **kwargs):
    #     book_query = self.get_queryset()
    #     book_ser = self.get_serializer(book_query, many=True)
    #     book_data = book_ser.data
    #     return APIResponse(results=book_data)

    # 单取
    def get(self, request, *args, **kwargs):
        book_query = self.get_object()
        book_ser = self.get_serializer(book_query)
        book_data = book_ser.data
        return APIResponse(results=book_data)

 

2 "mixins view toolset --- auxiliary GenericAPIView

# 1) There are five tools mixins class files, provided a total of five tools, six utility methods: single investigation, the investigation group, single by single deletion, a single overall change, a single partial change 
# 2) tools can inherit request functions to achieve simplification body, but must inherit GenericAPIView, several class attributes and methods (see above GenericAPIView knowledge base class) needs to provide GenericAPIView class 
# 3) tools tools method return value is a Response object, if you want to format formatted data back to the front, a response object tool can get method returns response data by response.data

Routing layer

urlpatterns = [
       url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),
]

View layer

from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin

class BookMixinGenericAPIView(ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            Response = self.retrieve (Request, * args, ** kwargs)
         the else :
             # response object list is provided a method mixins Response, like the object formatted APIResponse 
            Response = self.list (Request, args *, ** kwargs)
         # Response response.data data are stored in the 
        return APIResponse (Results = response.data)

    def post(self, request, *args, **kwargs):
        response = self.create(request, *args, **kwargs)
        return APIResponse(results=response.data)

    def put(self, request, *args, **kwargs):
        response = self.update(request, *args, **kwargs)
        return APIResponse(results=response.data)

    def patch(self, request, *args, **kwargs):
        response = self.partial_update(request, *args, **kwargs)
        return APIResponse(results=response.data)

 

3 "tool view

# 1) tool views are subclasses GenericAPIView, and the different sub-classes inherit different tools, rewrite the request method 
# 2) If the direct view function tool to meet the demand, only need to inherit tool view, provide queryset and can serializer_class

Routing layer

urlpatterns = [
       url(r'^v4/books/$', views.BookListCreatePIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreatePIView.as_view()),
]

View layer

from rest_framework.generics import ListCreateAPIView, UpdateAPIView
class BookListCreatePIView(ListCreateAPIView, UpdateAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

 

4 "View Set

# 1) is set priority inheritance ViewSetMixin view class, then the class inherits a view (GenericAPIView or APIView) 
#        GenericViewSet, Viewset 
# when 2) ViewSetMixin provides as_view rewritable () method of the view class inheritance viewset, configure routing call as_view () must pass request name - the function name dictionary mapping relationship 
#        EG: URL (R & lt '^ V5 / Books / $', views.BookGenericViewSet.as_view ({ 'GET': 'my_get_list'})), 
#        represents get requests to view function processing my_get_list

Routing layer

the urlpatterns = [
        # View of as_view (): the get request is mapped to the get method of the view class 
    # Viewset of as_view ({ 'get': ' my_get_list'}): the get request is mapped to my_get_list method of the view class of the 
    URL (R & lt ' V5 ^ / Books / $ ' , views.BookGenericViewSet.as_view ({ ' GET ' : ' my_get_list ' })),
    url(r'^v5/books/(?P<pk>.*)/$', views.BookGenericViewSet.as_view({'get': 'my_get_obj'})),
]

View layer

from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
class BookGenericViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    def my_get_list(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def my_get_obj(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

 

5 "The difference between the two most inherited view of GenericAPIView and APIView

# . 1) and GenericViewSet Viewset inherit ViewSetMixin, as_view can configure request - the function mapping 
# 2) GenericViewSet GenericAPIView view class inheritance is used to complete the standard model-based user interface 
# . 3) Viewset inherited APIView view class, used to complete the model class need not participate in, or non-standard model-based user interface 
#        post request under standard model-based operation is to add an interface, does not satisfy the landing post 
#        post interface to request a verification code, does not require the model class participate 
# authentication information login post request, the new data is not complete, but the data submitted by post, the results obtained are not logged in user information, but landing: case

 

6 "view tool set

Routing layer

urlpatterns = [
       url(r'^v6/books/$', views.BookModelViewSet.as_view({'get': 'list', 'post': 'create'})),
    url(r'^v6/books/(?P<pk>.*)/$', views.BookModelViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]

View layer

from rest_framework.viewsets import ModelViewSet
class BookModelViewSet(ModelViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    # Delete is not a database, but remove fields in the record 
    DEF the destroy (Self, Request, * args, ** kwargs):
        instance = self.get_object ()   # of the type: models.Book 
        IF  not instance:
             return APIResponse (1, ' Delete failed ' )   # actual operation, before it made a judgment 
        instance.is_delete = True
        instance.save()
        return APIResponse (0, ' deleted successfully ' )

 

7 "routing component (understand)

from django.conf.urls import include
from rest_framework.routers import SimpleRouter
Router = SimpleRouter ()
 # all routes with ViewSet view class can be registered, generate '^ v6 / books / $' and '^ v6 / books / (? P <pk> [^ /.] +) / $' 
router.register ( ' V6 / Books ' , views.BookModelViewSet)

the urlpatterns = [
     # a first mode to add a child list 
    URL (R & lt ' ^ ' , the include (router.urls)),
]
# The second way to add a sub-list 
# urlpatterns.extend (router.urls)

 

 

 

Guess you like

Origin www.cnblogs.com/xiaowangba9494/p/11708789.html