• drf 视图家族06


    视图家族类

    """ 视图家族
    from rest_framework import views, mixins, generics, viewsets
    
    views:视图类 - APIView,GenericAPIView(generics中)
    mixins:视图工具类 - CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
    generics:工具视图类 - 九个类
    viewsets:视图集 - 两个视图集基类,两个视图集子类,一个工具类
    """
    

    Generics工具视图类

    拥有APIView的所有
    
    from . import models, serializers
    from rest_framework.generics import GenericAPIView
    class CarGenericAPIView(GenericAPIView):
        # 不能直接写到objects结束,因为objects结束时,不是QuerySet对象,而是Manager对象,但 .all() 和 .filter() 后一定是QuerySet对象
        queryset = models.Car.objects.filter(is_delete=False).all()  # 源码self.queryset获取我们类内部的queryset,没有的话断言抛错  群查配置
        serializer_class = serializers.CarModelSerializer  # 源码告诉我们要自己定义一个序列化类  群查配置
        lookup_url_kwarg = 'pk' # 单查的配置
        
        # 群查
        def get(self, request, *args, **kwargs):
            # car_query = models.Car.objects.filter(is_delete=False).all()
            car_query = self.get_queryset()
    
            # car_ser = serializers.CarModelSerializer(instance=car_query, many=True)
            car_ser = self.get_serializer(car_query, many=True)
            return APIResponse(results=car_ser.data)
        
          # 单查
        def get(self, request, *args, **kwargs):
            # pk = kwargs.get('pk')
            # car_obj = models.Car.objects.filter(is_delete=False).filter(pk=pk).first()
            car_obj = self.get_object()
    
            # car_ser = serializers.CarModelSerializer(car_obj)
            car_ser = self.get_serializer(car_obj)
    
            return APIResponse(results=car_ser.data)
    
    

    源码分析

    get_queryset()

    自己类内部有queryset属性,就是数据库查出的queryset对象
    

    get_serializer(car_query, many=True)

    serializer_class = serializers.CarModelSerializer # 自己类内部指向序列化类
    

    get_object()

     我们的类中配置:lookup_url_kwarg = 'pk',且pk要与url中的有名分组写的参数一致,不然内部源码找的是我们的配置的参数,然后抛错。
    

    mixins:视图工具类

    调用GenericAPIView视图类内部的方法,进行进一步的封装,做单查,群查,单增操作
    
    # urls.py
    urlpatterns = [
        url(r'^v3/cars/$', views.CarReadGenericAPIView.as_view()),
        url(r'^v3/cars/(?P<pk>d+)/$', views.CarReadGenericAPIView.as_view()),
    ]
    
    # views.py
    
    from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, CreateModelMixin
    class CarReadCreateGenericAPIView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, GenericAPIView):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
        lookup_url_kwarg = 'pk'
        
        # 群查
        def get(self, request, *args, **kwargs):
            # car_query = self.get_queryset()
            # car_ser = self.get_serializer(car_query, many=True)
            # return APIResponse(results=car_ser.data)
            return self.list(request, *args, **kwargs)
    
        # 单查
    
        def get(self, request, *args, **kwargs):
            # car_obj = self.get_object()
            # car_ser = self.get_serializer(car_obj)
            # return APIResponse(results=car_ser.data)
            response = self.retrieve(request, *args, **kwargs)
            # 返回方式一:
            return response
        	# 返回方式二:使用自定义响应
            # return APIResponse(results=response.data)
      
     # 单增
        def post(self, request, *args, **kwargs):
            return self.create(request, *args, **kwargs)
    

    源码分析

     群查:self.list(request, *args, **kwargs)  # 内部封装了Response方法
    
    # 群增源码操作
    
    class ListModelMixin:
        """
        List a queryset.
        """
        def list(self, request, *args, **kwargs):
            # 先去自己类中找get_queryset方法,再去ListModelMixin,如果没有去GenericView中找,
            # ListModelMixin和GenericView之间没哟继承关系,但我们写的类继承他俩,
            # self(我们的类对象就可以夸两个父类去查找方法)
            queryset = self.filter_queryset(self.get_queryset())
    
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
    
            serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)
    
    单查:self.retrieve(request, *args, **kwargs)
    
    class RetrieveModelMixin:
        """
        Retrieve a model instance.
        """
        def retrieve(self, request, *args, **kwargs):
            instance = self.get_object()
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
    
    单增:
    
    class CreateModelMixin:
        """
        Create a model instance.
        """
        def create(self, request, *args, **kwargs):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            # 将序列化的serializer.data结果直接返回给前台,如果包
            # 含用户密码等安全信息,显然不合适,所有不建议只用该方法做单增操作
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
        def perform_create(self, serializer):
            serializer.save()
    
        def get_success_headers(self, data):
            try:
                return {'Location': str(data[api_settings.URL_FIELD_NAME])}
            except (TypeError, KeyError):
                return {}
    
    

    Generics工具视图类(单独完成封装)

    我们定义的视图类里面没有定义对应的单查、群查、( 单查(get)、单整体改(put)、单局部改(patch)、单删接口(delete))等接口dispatch会到继承的类中去查找这些方法,我们只需要把对应的方法实现体的配置按源码要求写好就可以实现序列化,反序列化,及响应过程。
    

    views.py代码

    # 单独完成单查接口
    from rest_framework.generics import RetrieveAPIView
    class CarRetrieveAPIView(RetrieveAPIView):  
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
        lookup_url_kwarg = 'pk'
    
    # 单独完成群查接口
    from rest_framework.generics import ListAPIView
    class CarListAPIView(ListAPIView):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
    
    
    # 单查(get)、单整体改(put)、单局部改(patch)、单删接口(delete)
    from rest_framework.generics import RetrieveUpdateDestroyAPIView
    class CarRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
    

    内部源码

    单独完成单查接口
    
    class RetrieveAPIView(mixins.RetrieveModelMixin,
                          GenericAPIView):
        """
        Concrete view for retrieving a model instance.
        """
        def get(self, request, *args, **kwargs):
            return self.retrieve(request, *args, **kwargs)
    
    单独完成群查接口
    
    class ListAPIView(mixins.ListModelMixin,
                      GenericAPIView):
        """
        Concrete view for listing a queryset.
        """
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    
    class RetrieveAPIView(mixins.RetrieveModelMixin,  
                          GenericAPIView):
        """
        Concrete view for retrieving a model instance.
        """
        def get(self, request, *args, **kwargs):
            return self.retrieve(request, *args, **kwargs)
    
    单查(get)、单整体改(put)、单局部改(patch)、单删接口(delete)
    
    class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
                                       mixins.UpdateModelMixin,
                                       mixins.DestroyModelMixin,
                                       GenericAPIView):
        """
        Concrete view for retrieving, updating or deleting a model instance.
        """
        def get(self, request, *args, **kwargs):
            return self.retrieve(request, *args, **kwargs)
    
        def put(self, request, *args, **kwargs):
            return self.update(request, *args, **kwargs)
    
        def patch(self, request, *args, **kwargs):
            return self.partial_update(request, *args, **kwargs)
    
        def delete(self, request, *args, **kwargs):
            return self.destroy(request, *args, **kwargs)
    

    总结

    """
    1、APIView:
    1)拥有View的所有  2)重写as_view  3)重写dispatch  4)一系列类属性
    
    
    2、GenericAPIView
    1)继承APIView,所以拥有APIView的所有
    2)get_queryset方法,配置queryset类属性,提供视图类相关的Models
    3)在第二条基础上,get_object方法,配置lookup_url_kwarg类属性,提供视图类相关的具体Model
    4)get_serializer方法,配置serializer_class类属性,提供视图类相关的序列化对象
    
    总结:GenericAPIView就是在APIView基础上额外提供了三个方法,三个类属性,如果不配合视图工具类,体现不出优势
    目的:视图中的增删改查逻辑相似,但操作的资源不一致,操作资源就是操作 资源对象们、资源对象以及资源相关的序列化类,
    将这三者形成配置,那操作逻辑就一致,就可以进行封装
    
    3、mixins视图工具类们:五个类,六个方法
    1)要配合GenericAPIView类使用,将单查、群查、单增,单整体改,单局部改,单删六个接口
    封装成retrieve、list、create、update、partial_update、destroy六个方法
    原因:六个方法的实现体,调用的方法就是GenericAPIView提供的,所以要配合GenericAPIView类使用
    
    4、generics工具视图类们:九种组合
    1)帮我们将不同个数不同种类的mixins与GenericAPIView进行组合
    2)不同的组合帮我们实现好对应的get、post、put、patch、delete方法
    3)需要我们自己配置三个类属性即可:queryset、serializer_class、lookup_url_kwarg
    """
    """
    class CarView(APIView):
        def get(self):
            obj,
            ser,
            response,
            
    class CarView(GenericAPIView):  # 不会出现,中间产物
        queryset,
        serializer_class,
        lookup_url_kwarg,
        def get(self):
            obj,
            ser,
            response,
    
    class CarView(RetrieveModelMixin, GenericAPIView):  # 自定义组合,可以超过九种
        queryset,
        serializer_class,
        lookup_url_kwarg,
        def get(self):
            self.retrieve()
            
    class CarView(RetrieveAPIView):  # 最终产物,系统只提供了九种组合,RetrieveAPIView是其中一种
        queryset,
        serializer_class,
        lookup_url_kwarg,
    """
    

    视图集

    """ 视图集总结
    核心:视图集都继承了 ViewSetMixin类,该类重写了as_view方法,相比APIView的as_view方法,额外多出了一个参数actions
        as_view({'get': 'list'}) 传入的{'get': 'list'}就被actions介绍,原理是将get请求映射给视图类的list函数进行处理
    
    1)为什么有GenericViewSet和ViewSet两个视图集基类
        GenericViewSet(ViewSetMixin, GenericAPIView),该分支严格满足资源接口
        ViewSet(ViewSetMixin, APIView),该分支满足的接口与资源Model类关系不是特别密切:登录接口、短信验证码接口
    
    2)ReadOnlyModelViewSet,ModelViewSet两个视图集子类,就是做个一堆mixin与GenericViewSet相结合,
        自己在urls文件中配置as_view设置映射关系
    """
    
    urlpatterns = [
         # 视图集
        # url(r'^v6/cars/$', views.CarReadOnlyAPIView.as_view({'get': 'many_get'})),
        # url(r'^v6/cars/(?P<pk>d+)/$', views.CarReadOnlyAPIView.as_view({'get': 'single_get'})),
        
        url(r'^v6/cars/$', views.CarReadOnlyAPIView.as_view({'get': 'list'})),
        url(r'^v6/cars/(?P<pk>d+)/$', views.CarReadOnlyAPIView.as_view({'get': 'retrieve'})),
    ]
    
    # 视图集
    from rest_framework.viewsets import ViewSetMixin, GenericViewSet, ViewSet, ModelViewSet
    class CarReadOnlyAPIView(RetrieveModelMixin, ListModelMixin, GenericViewSet):
        # def many_get(self, request, *args, **kwargs):
        #     return self.list(request, *args, **kwargs)
        #
        # def single_get(self, request, *args, **kwargs):
        #     return self.retrieve(request, *args, **kwargs)
    
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
    

    源码分析

    ViewSetMixin类内部重写了as_view方法,我们的类继承了GenericViewSet类,所以查找就是ViewSetMixin类内部的as_view方法;路由传过来的参数(字典形式)匹配我们视图类中的函数是源码做的限制,让as_view方法的形参actions=None接受了,内部利用反射的getattr、setattr方法将视图函数的内存地址塞到视图类的对象中去,并调用dispatch方法做分发,而dispatch的查找顺序有如何呢?
    首先我们自己定义的视图类内部没有,去GenericViewSet查找,而它内部并没有代码(只做分发),但是他继承了generics.GenericAPIView,GenericAPIView又继承了views.APIView,APIView又继承了父类的as_view()方法,所以最终dispatch还是在View类找到的,并做的分发。
    
    class ViewSetMixin:
        """
        This is the magic.
    
        Overrides `.as_view()` so that it takes an `actions` keyword that performs
        the binding of HTTP methods to actions on the Resource.
    
        For example, to create a concrete view binding the 'GET' and 'POST' methods
        to the 'list' and 'create' actions...
    
        view = MyViewSet.as_view({'get': 'list', 'post': 'create'})
        """
        @classonlymethod
        def as_view(cls, actions=None, **initkwargs):
            cls.name = None
            cls.description = None
            cls.suffix = None
            cls.detail = None
            cls.basename = None
            if not actions:
                raise TypeError("The `actions` argument must be provided when "
                                "calling `.as_view()` on a ViewSet. For example "
                                "`.as_view({'get': 'list'})`")
    
            # sanitize keyword arguments
            for key in initkwargs:
                if key in cls.http_method_names:
                    raise TypeError("You tried to pass in the %s method name as a "
                                    "keyword argument to %s(). Don't do that."
                                    % (key, cls.__name__))
                if not hasattr(cls, key):
                    raise TypeError("%s() received an invalid keyword %r" % (
                        cls.__name__, key))
    
            # name and suffix are mutually exclusive
            if 'name' in initkwargs and 'suffix' in initkwargs:
                raise TypeError("%s() received both `name` and `suffix`, which are "
                                "mutually exclusive arguments." % (cls.__name__))
    
            def view(request, *args, **kwargs):
                self = cls(**initkwargs)
                self.action_map = actions
                for method, action in actions.items():
                    handler = getattr(self, action)
                    # 将get请求绑定many_get函数地址,在dispatch方法分发get请求是many_get函数响应
                    setattr(self, method, handler)
                if hasattr(self, 'get') and not hasattr(self, 'head'):
                    self.head = self.get
    
                self.request = request
                self.args = args
                self.kwargs = kwargs
                return self.dispatch(request, *args, **kwargs)
    
            update_wrapper(view, cls, updated=())
            update_wrapper(view, cls.dispatch, assigned=())
            view.cls = cls
            view.initkwargs = initkwargs
            view.actions = actions
            return csrf_exempt(view)
    

    调用dispatch经过的类代码

    class ViewSet(ViewSetMixin, views.APIView):
        """
        The base ViewSet class does not provide any actions by default.
        """
        pass
    
    
    class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
        """
        The GenericViewSet class does not provide any actions by default,
        but does include the base set of generic view behavior, such as
        the `get_object` and `get_queryset` methods.
        """
        pass
    

    基于视图集中的ModelViewSet类实现的六大接口

    群查、单增、单查、整体单改、局部单改、单删
    
    # urls.py
    
    urlpatterns = [
      url(r'^v7/cars/$', views.CarModelViewSet.as_view({
            'get': 'list',
            'post': 'create',
        })),
        url(r'^v7/cars/(?P<pk>d+)/$', views.CarModelViewSet.as_view({
            'get': 'retrieve',
            'put': 'update',
            'patch': 'partial_update',
            'delete': 'destroy',
        })),
    ]
    
    # views.py
    from rest_framework.viewsets import ViewSetMixin, GenericViewSet, ViewSet, ModelViewSet
    class CarModelViewSet(ModelViewSet):
    	queryset = models.Car.objects.filter(is_delete=False).all()
         serializer_class = serializers.CarModelSerializer
        # 分析:从实际开发角度分析不合理点
        # 1)没有群增,群整体改,群局部改,群删四个接口
        # 2)删除操作视图集默认走的destroy方法是将资源从数据库中删除,通常一个做字段is_delete字段修改表示删除
        # 3)响应的结果只有数据,没有数据状态码和状态信息
    

    源码分析

    class ModelViewSet(mixins.CreateModelMixin,
                       mixins.RetrieveModelMixin,
                       mixins.UpdateModelMixin,
                       mixins.DestroyModelMixin,
                       mixins.ListModelMixin,
                       GenericViewSet):
        """
        A viewset that provides default `create()`, `retrieve()`, `update()`,
        `partial_update()`, `destroy()` and `list()` actions.
        """
        pass
    

    实际开发中的视图集的使用

    # urls.py
    urlpatterns = [
        url(r'^v7/cars/$', views.CarModelViewSet.as_view({
            'post': 'create',
            'put': 'many_update',
            'patch': 'many_partial_update',
            'delete': 'many_destroy',
        })),
        url(r'^v7/cars/(?P<pk>d+)/$', views.CarModelViewSet.as_view({
            'delete': 'destroy',
        })),
    ]
    
    class CarModelViewSet(ModelViewSet):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
        # 分析:从实际开发角度分析不合理点
        # 1)没有群增,群整体改,群局部改,群删四个接口
        # 2)删除操作视图集默认走的destroy方法是将资源从数据库中删除,通常一个做字段is_delete字段修改表示删除
        # 3)响应的结果只有数据,没有数据状态码和状态信息
    
        # 解决1,
        # 群整体改,群局部改,全删三个接口可以独立成三个方法
        def many_update(self, request, *args, **kwargs):
            return APIResponse(msg='这个地方是群整体改,你会写!')
        def many_partial_update(self, request, *args, **kwargs):
            return APIResponse(msg='这个地方是群局部改,你会写!')
        def many_destroy(self, request, *args, **kwargs):
            return APIResponse(msg='这个地方是群删,你会写!')
        # 群增与单增必须公用一个接口,都要走create方法 - 重写create方法,用逻辑进行拆分
        def create(self, request, *args, **kwargs):
            request_data = request.data
            if isinstance(request_data, list):
                car_ser = self.get_serializer(data=request_data, many=True)
                car_ser.is_valid(raise_exception=True)
                car_obj = car_ser.save()
                return APIResponse(msg='群增成功', results=self.get_serializer(car_obj, many=True).data)
    
            return super().create(request, *args, **kwargs)
    
    
        # 解决2,destroy方法是完成is_delete字段值修改 - 重写destroy方法,自定义实现体
        def destroy(self, request, *args, **kwargs):
            car_obj = self.get_object()
            car_obj.is_delete = True
            car_obj.save()
            return APIResponse(msg='删除成功')
    
    
        # 解决3,让群查有状态码和状态信息 - 重写list方法
        def list(self, request, *args, **kwargs):
            response = super().list(request, *args, **kwargs)
            return APIResponse(results=response.data)
    

    视图集路由层

    from rest_framework.routers import SimpleRouter
    router = SimpleRouter()
    router.register('v7/cars', views.CarModelViewSet, basename='car')
    # router.register('books', views.BookModelViewSet, basename='book')
    # router.register('users', views.UserModelViewSet, basename='user')
    # urlpatterns.extend(router.urls)
    print(router.urls)
    

    视图家族小总结:点我吊我

  • 相关阅读:
    一个Windows的对话框
    怎样用Javascript定义一个类
    WPF 开源UI框架
    企业级系统的认证与授权设计
    MVC (ModelBinder等)技巧
    oracle 调用存储过程和方法
    WPF相关文章索引 (持续更新中)
    当文件操作遇上进程占用时
    每位设计师都应该拥有的50个CSS代码片段
    wpf 复制/剪切到本地系统剪切板中以供右键粘贴用
  • 原文地址:https://www.cnblogs.com/zhangchaocoming/p/12122508.html
Copyright © 2020-2023  润新知