zoukankan      html  css  js  c++  java
  • Django Rest Framework --- 视图组件

    一、视图组件的作用

      在每一个视图类中都写请求方法,并且书写请求逻辑时,这样做会大大增加开发的时间,因此我们可以对这一类利用面向对象的封装来解决。

    二、手动封装视图类

    • views.py
    # 获取全部数据
    class List:
        def list(self, request):
            query_set_list = self.query_set_list
            data_serializer = self.ser(query_set_list, many=True)
            response = {"status": 100, "message": "数据获取成功"}
            response['data'] = data_serializer.data
            return Response(response)
    
    
    # 创建新数据
    class Create:
        def create(self, request):
            data_serializer = self.ser(data=request.data)
            # 数据校验
            if data_serializer.is_valid():
                data_serializer.save()
                response = {"status": 100, "message": "创建用户成功", "data": data_serializer.data}
            else:
                response = {"status": 100, "message": data_serializer.errors, "data": ""}
            return Response(response)
    
    
    # 获取一个数据
    class GetOne:
        def get_one(self, request, pk):
            query_set_obj = self.query_set_list.filter(pk=pk).first()
            if query_set_obj:
                data_serializer = self.ser(query_set_obj, many=False)
                response = {"status": 100, "message": "获取数据成功", "data": data_serializer.data}
                return Response(response)
            else:
                response = {"status": 100, "message": "该数据不存在", "data":""}
                return Response(response)
    
    #修改数据
    class Update:
        def update(self,request,pk):
            query_set_obj = self.query_set_list.filter(pk=pk).first()
            if query_set_obj:
                data_serializer = self.ser(instance=query_set_obj,data=request.data)
                if data_serializer.is_valid():
                    data_serializer.save()
                    response = {"status":100,"message":"数据修改成功","data":data_serializer.data}
                else:
                    response = {"status": 100, "message": data_serializer.errors, "data":""}
            else:
                response = {"status": 100, "message": "需要修改的数据不存在", "data": ""}
            return Response(response)
    
    #删除数据
    class Delete:
        def delete_by_id(self,request,pk):
            query_set_obj = self.query_set_list.filter(pk=pk).first()
            if query_set_obj:
                query_set_obj.delete()
                response = {"status": 100, "message": "数据删除成功", "data": ""}
            else:
                response = {"status": 100, "message": "需要删除的数据不存在", "data": ""}
            return Response(response)
    
    
    
    
    class BooksView(List, Create, APIView):
        query_set_list = models.Book.objects.all()
        ser = BookSerializers
    
        def get(self, request):
            return self.list(request)
    
        def post(self, request):
            return self.create(request)
    
    
    class BookView(GetOne,Update,Delete,APIView):
        query_set_list = models.Book.objects.all()
        ser = BookSerializers
    
        def get(self, request, pk):
            return self.get_one(request,pk)
    
        def put(self,request,pk):
            return self.update(request,pk)
    
        def delete(self,request,pk):
            return self.delete_by_id(request,pk)
    • urls.py
    from app01.views import BooksView,BookView
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^Books/$', BooksView.as_view()),
        url(r'^Books/(?P<pk>d+)$', BookView.as_view()),
        ]

    三、rest framework视图组件之mixin类和generice类编写视图

      本质其实就是上面的封装视图的过程,在返回数据等方面有一些不同。

    • views.py
    from rest_framework.mixins import CreateModelMixin,UpdateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin
    from rest_framework.generics import GenericAPIView
    
    #查询所有数据和创建新数据的视图
    class BooksView(ListModelMixin,CreateModelMixin,GenericAPIView):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializers
        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 BookView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializers
    
        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 delete(self,request,*args,**kwargs):
            return self.destroy(request,*args,**kwargs)

    四、rest framework视图组件之使用generics下ListCreateAPIView,RetrieveUpdateDestroyAPIViewn编写视图

    • views.py
    from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
    
    class BooksView(ListCreateAPIView):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializers
    
    class BookView(RetrieveUpdateDestroyAPIView):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializers

    五、rest framework视图组件之使用ModelViewSet编写视图

    • views.py
    from rest_framework.viewsets import ModelViewSet
    
    class BooksView(ModelViewSet):
        queryset = models.Book.objects.all()
        serializer_class = BookSerializers
    • urls.py
    from app01.views import BooksView
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^Books/$', BooksView.as_view({"get":"list","post":"create"})),
        url(r'^Books/(?P<pk>d+)$', BooksView.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
        ]
  • 相关阅读:
    理解mipi协议【转】
    Using KernelShark to analyze the real-time scheduler【转】
    内核栈溢出【转】
    检测内核的堆栈溢出【转】
    gcc 编译 + 选项【转】
    service mysqld start 报错:service mysqld start 报错 090517 13:34:15 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it. 090Can't open the mysql.plugin table. Please run mysql
    【推荐】MySQL Cluster报错及解决方法(不断更新中)
    MySQL Cluster 配置文件(config.ini)详解
    关于MySQL Cluster集群NoOfReplicas参数问题
    通过PHP current()函数获取未知字符键名数组第一个元素的值
  • 原文地址:https://www.cnblogs.com/846617819qq/p/10608908.html
Copyright © 2011-2022 走看看