码迷,mamicode.com
首页 > 其他好文 > 详细

drf 视图的三种继承

时间:2019-11-30 19:26:17      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:def   upd   port   api   elm   变化   objects   参数   pytho   

视图的方法(继承)

  • 第一种:原始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)等。不需手写get\post等方法。

    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 视图的三种继承

标签:def   upd   port   api   elm   变化   objects   参数   pytho   

原文地址:https://www.cnblogs.com/yzm1017/p/11963490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!