drf 视图的三种继承

Posted yzm1017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了drf 视图的三种继承相关的知识,希望对你有一定的参考价值。

视图的方法(继承)

  • 第一种:原始APIView

    需要自己写get/post方法。

    url(r'^login/$',account.LoginView.as_view()),
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework_jwt.settings import api_settings
    from rest_framework.throttling import AnonRateThrottle
    from api import models
    
    
    class LoginView(APIView):
        authentication_classes = []
        def post(self,request,*args,**kwargs):
            # 1.根据用户名和密码检测用户是否可以登录
            user = models.UserInfo.objects.filter(username=request.data.get('username'),password=request.data.get('password')).first()
            if not user:
                return Response({'code':10001,'error':'用户名或密码错误'})
    
            # 2. 根据user对象生成payload(中间值的数据)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            payload = jwt_payload_handler(user)
    
            # 3. 构造前面数据,base64加密;中间数据base64加密;前两段拼接然后做hs256加密(加盐),再做base64加密。生成token
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            token = jwt_encode_handler(payload)
            return Response({'code': 10000, 'data': token})
  • 第二种:ListAPIView(多个数据的get)、RetrieveAPIView(单个数据的get)、CreateAPIView(post)、DestroyAPIView(delete)、UpdateAPIView(put/patch)等。不需手写getpost等方法。

    url(r'^article/$',article.ArticleView.as_view()),
    url(r'^article/(?P<pk>d+)/$',article.ArticleDetailView.as_view()),
    from rest_framework.throttling import AnonRateThrottle
    from rest_framework.response import Response
    from rest_framework.generics import ListAPIView, RetrieveAPIView
    from api import models
    from api.serializer.article import ArticleSerializer,ArticleDetailSerializer
    
    class ArticleView(ListAPIView):
        """文章列表"""
        authentication_classes = []
        # throttle_classes = [AnonRateThrottle,]
    
        queryset = models.Article.objects.all()
        serializer_class = ArticleSerializer
    
    class ArticleDetailView(RetrieveAPIView):
        """单个文章"""
        authentication_classes = []
        queryset = models.Article.objects.all()
        serializer_class = ArticleDetailSerializer
  • 第三种:ListModelMixin,RetrieveModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin等。它们内部都有自己对应的方法。

    需要在路由开始写对应关系。

    路由:

    url(r'^article/$',article.ArticleView.as_view({"get":'list','post':'create'})),
    
    url(r'^article/(?P<pk>d+)/$',article.ArticleView.as_view({'get':'retrieve','put':'update','patch':'partial_update','delete':'destroy'}))

    视图:

    from rest_framework.viewsets import GenericViewSet
    from rest_framework.mixins import ListModelMixin,RetrieveModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin
    from api.serializer.article import ArticleSerializer,ArticleDetailSerializer
    
    class ArticleView(GenericViewSet,ListModelMixin,RetrieveModelMixin,):
        """获取文章列表以及单条文章"""
        authentication_classes = []
        throttle_classes = [AnonRateThrottle,]
    
        queryset = models.Article.objects.all()
        serializer_class = None
    
        def get_serializer_class(self):
            pk = self.kwargs.get('pk')
            if pk:
                return ArticleDetailSerializer
            return ArticleSerializer
    

    总结:

    APIView,只提供了基础的功能,有版本、认证、权限、节流等功能,但没有增删改查的功能;
    ListAPIView等, 继承APIView,提供增删改查的功能,不用自己写get/post方法;
    ListModelMixin等, 路由就需发生变化,传参数{"get":‘list‘},表示是get方式,并且是list方法。这样就可以将 获取多个(列表)和获取一个 放在一个类里。

以上是关于drf 视图的三种继承的主要内容,如果未能解决你的问题,请参考以下文章

django-缓存的三种应用

DRF视图

DRF视图

DRF视图 𵀝

drf视图类的继承关系

DRF视图 -- 2019-08-08 18:01:40