rest-framework总结

Posted geogre123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rest-framework总结相关的知识,希望对你有一定的参考价值。

1. CBV:

pass

2 .APIView

class BookView(APIView):pass
url(r^books/$, views.BookView.as_view(),name="books"),
url(r^books/$, View类下的view,name="books"),
一旦访问books/: view(request)======APIView类下的dispatch()====请求方式对应的示例方法()

3 def dispatch():

 #一 初始化操作
      # (1) 构建新的request:
      self.request=self.initial_request()
      # self.request._request
      # self.request.GET
      # self.request.data
      # (2) 执行组件
      # 认证,权限,频率
      # 认证:request.user
      self.initial(request, *args, **kwargs)
                 ====   # 认证组件
                        self.perform_authentication(request)
                           ==== request.user
                                     ===== 
                                          for authenticator in self.authenticators:  # [TokenAuth(),]
                                                    try:
                                                        user_auth_tuple = authenticator.authenticate(self)
                                                    except exceptions.APIException:
                                                        self._not_authenticated()
                                                        raise

                                                    if user_auth_tuple is not None:
                                                        self._authenticator = authenticator
                                                        self.user, self.auth = user_auth_tuple
                                                        return
                        
                        
                        # 权限组件
                        self.check_permissions(request)
                           ===========
                                 for permission in self.get_permissions():
                                        if not permission.has_permission(request, self):
                                            self.permission_denied(
                                                request, message=getattr(permission, message, None)
                                            )
                        
                        
                        # 频率组件
                        self.check_throttles(request)
                        
                          =============
                            for throttle in self.get_throttles():  # [VisitRateThrottle(),]
                                    if not throttle.allow_request(request, self):
                                        self.throttled(request, throttle.wait()) # 受限制
                       
                        
       # 分发
            if request.method.lower() in self.http_method_names:
                handler = getattr(self,request.method.lower(),
                                  self.http_method_not_allowed)
        
            response = handler(request, *args, **kwargs)
            
            return response

4 序列化组件

class PublishSerializers(serializers.Serializer):
            name = serializers.CharField()
            email = serializers.CharField()
                    
    class PublishModelSerializers(serializers.ModelSerializer):
            class Meta:
                model=Publish
                fields="__all__"
    
    # queryset或者model对象-------------》json数据
    ps=PublishSerializers(queryset,many=True)
    ps.data # [{},{},{}]
    
    #model对象
    ps=PublishSerializers(model_obj,many=False)
    ps.data # {}
    
    
    # json数据-------》记录
    # 添加操作
    ps=PublishSerializers(data=request.data)
    if ps.is_valid():  #必须进行is_vaid校验
       ps.save()  # create
       
       
    # 更新操作
    ps=PublishSerializers(model_obj,data=request.data)
    if ps.is_valid():
       ps.save()  # update
    

5 .视图组件

版本1(逻辑复用版本):

# Book表
            class BookView(APIView):
                def get(self,request):
                    book_list=Book.objects.all()
                    bs=BookModelSerializers(book_list,many=True,context={request: request})
                    return Response(bs.data)        
                def post(self,request):
                    # post请求的数据
                    bs=BookModelSerializers(data=request.data)
                    if bs.is_valid():
                        print(bs.validated_data)
                        bs.save()# create方法
                        return Response(bs.data)
                    else:
                        return Response(bs.errors)

            class BookDetailView(APIView):

                def get(self,request,id):

                    book=Book.objects.filter(pk=id).first()
                    bs=BookModelSerializers(book,context={request: request})
                    return Response(bs.data)

                def put(self,request,id):
                    book=Book.objects.filter(pk=id).first()
                    bs=BookModelSerializers(book,data=request.data)
                    if bs.is_valid():
                        bs.save()
                        return Response(bs.data)
                    else:
                        return Response(bs.errors)

                def delete(self,request,id):
                    Book.objects.filter(pk=id).delete()

                    return Response()

版本2(mixIn):

    #虽然逻辑封装了,但是依旧代码复用。
        from rest_framework import mixins
        from rest_framework import generics

        class AuthorView(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
            queryset=Author.objects.all()
            serializer_class =AuthorModelSerializers

            def get(self,request, *args, **kwargs):
                return self.list(request, *args, **kwargs)
            def post(self,request, *args, **kwargs):
                return self.create(request, *args, **kwargs)


        class AuthorDetailView(mixins.RetrieveModelMixin,mixins.DestroyModelMixin,mixins.UpdateModelMixin,generics.GenericAPIView):
            queryset = Author.objects.all()
            serializer_class = AuthorModelSerializers

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

            def delete(self,request,*args, **kwargs):
                return self.destroy(request,*args, **kwargs)

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

版本3:基于通用类

from rest_framework import mixins
        from rest_framework import generics

        #增和查封装
        class AuthorView(generics.ListCreateAPIView):
            queryset=Author.objects.all()
            serializer_class =AuthorModelSerializers
    
        #更新,单条查看, 删除封装
        class AuthorDetailView(generics.RetrieveUpdateDestroyAPIView):
            queryset = Author.objects.all()
            serializer_class = AuthorModelSerializers

版本4:最终版

    #在url上做了区分,使用同一个视图
     from rest_framework import viewsets
    class AuthorModelView(viewsets.ModelViewSet):
        queryset=Author.objects.all()
        serializer_class=AuthorModelSerializers
            
     url(r^authors/$, views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"),
     url(rauthors/(?P<pk>d+)/$, views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}),name="authordetail"),

最终版的流程:

 流程:
         url(r^authors/$, views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"),
         url(r^authors/$, ViewSetMixin下的.as_view({"get":"list","post":"create"}),name="author"),
         url(r^authors/$, ViewSetMixin类下的view),
         一旦访问 /authors/:
              ViewSetMixin
             def  view():
                #做了一个反射,将url传参的键值拿到,取get以后取到就是list,post就是create
                for method, action in actions.items(): # {"get":"list","post":"create"}
                    handler = getattr(self, action)    # self.list  self.create
                    setattr(self, method, handler)            
                              
                self.dispatch(request, *args, **kwargs)
            
            APIView类下的self.dispatch
                  # 分发(上面做完反射以后分发)
                    if request.method.lower() in self.http_method_names:
                        handler = getattr(self,request.method.lower(),
                                          self.http_method_not_allowed)
                
                    response = handler(request, *args, **kwargs) # self.list()    
                    return response

 

以上是关于rest-framework总结的主要内容,如果未能解决你的问题,请参考以下文章

如何解决 django rest-framework 中的错误请求

rest-framework框架的基本组件

rest-framework之版本控制

rest-framework之权限组件

如何优化查询 django rest-framework

Django rest-framework框架-组件之渲染器