首页 > 其他 > 详细

lf-M9-cp2-13 视图组件

时间:2019-02-25 22:27:25      阅读:184      评论:0      收藏:0      [点我收藏+]

APIView和View的区别


APIView 是对 View 的封装


技术分享图片


视图的第一次封装

技术分享图片


GenericAPIView 是对 APIView 的封装 
xxxMixin  是对处理的各种请求方法的封装
技术分享图片
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from .serializers import BookSerializer




class GenericAPIView(APIView):
    query_set = None
    serializer_class = None

    def get_queryset(self):
        return self.query_set

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)


class ListModelMixin(object):
    def list(self, request):
        queryset = self.get_queryset()
        ret = self.get_serializer(queryset, many=True)
        return Response(ret.data)


class CreateModelMixin(object):
    def create(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)


class RetrieveModelMixin(object):
    def retrieve(self, request, id):
        book_obj = self.get_queryset().filter(id=id).first()
        ret = self.get_serializer(book_obj)
        return Response(ret.data)


class UpdateModelMixin(object):
    def update(self, request, id):
        book_obj = self.get_queryset().filter(id=id).first()
        serializer = self.get_serializer(book_obj, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)


class DestroyModelMixin(object):
    def destroy(self, request, id):
        book_obj = self.get_queryset().filter(id=id).first()
        book_obj.delete()
        return Response("")


class ListCreateAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    pass


class RetrieveUpdateDestroyAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    pass


# class BookView(GenericAPIView, ListModelMixin, CreateModelMixin):
class BookView(ListCreateAPIView):
    query_set = Book.objects.all()      # 操作的表的对象
    serializer_class = BookSerializer   # 序列化的类

    def get(self, request):
        # book_obj = Book.objects.first()
        # ret = BookSerializer(book_obj)
        # book_list = Book.objects.all()
        # book_list = self.get_queryset()
        # ret = self.get_serializer(book_list, many=True)
        # return Response(ret.data)
        return self.list(request)

    def post(self, request):
        # print(request.data)
        # serializer = BookSerializer(data=request.data)
        # if serializer.is_valid():
        #     serializer.save()
        #     return Response(serializer.data)
        # else:
        #     return Response(serializer.errors)
        return self.create(request)


# class BookEditView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
class BookEditView(RetrieveUpdateDestroyAPIView):
    query_set = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request, id):
        # book_obj = Book.objects.filter(id=id).first()
        # ret = BookSerializer(book_obj)
        # return Response(ret.data)
        return self.retrieve(request, id)

    def put(self, request, id):
        # book_obj = Book.objects.filter(id=id).first()
        # serializer = BookSerializer(book_obj, data=request.data, partial=True)
        # if serializer.is_valid():
        #     serializer.save()
        #     return Response(serializer.data)
        # else:
        #     return Response(serializer.errors)
        return self.update(request, id)

    def delete(self, request, id):
        # book_obj = Book.objects.filter(id=id).first()
        # book_obj.delete()
        # return Response("")
        return self.destroy(request, id)
视图的第一次封装


视图的第二次封装


class ListCreateAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    pass

class RetrieveUpdateDestroyAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    pass

class BookView(ListCreateAPIView):
    pass

class BookEditView(RetrieveUpdateDestroyAPIView):
    pass


视图的第三次封装


因为是按照请求的方式不同反回的结果,所有第二次有两个视图函数


现在指定一个视图函数

  # 视图类传参,不同的请求对应不同的方法
    path(‘list‘, BookModelViewSet.as_view({"get": "list", "post": "create"})),
    path(‘retrieve/<int:pk>‘, BookModelViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),


# class ViewSetMixin(object):
#     def as_view(self):
#         """
#         按照我们参数指定的去匹配 对应的方法
#         get-->list
#         :return: 不用我们去写,框架有
#         """


ViewSetMixin 请求分发方法的原理,将不同的请求设置为不同的方法

技术分享图片


from rest_framework.viewsets import ViewSetMixin

class ModelViewSet(ViewSetMixin, GenericAPIView, ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    pass

# from rest_framework.viewsets import ModelViewSet
#  框架内部已经实现了的,可以直接导入
#
class BookModelViewSet(ModelViewSet):
    
    query_set = Book.objects.all() 自己封装的query_set
  # queryset = Book.objects.all() # 框架的是queryset
serializer_class = BookSerializer

from rest_framework import views     # APIView
from rest_framework import generics # GenericAPIView, 组合类
from rest_framework import mixins #混合继承类
from rest_framework import viewsets # ViewSetMixin 分发请求的类


技术分享图片


用框架的时

路由为

 path(‘retrieve/<int:pk>‘, BookModelViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),


前面自己定义的是id,用框架时注意修改过来

 path(‘retrieve/<int:id>‘, BookModelViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),


技术分享图片

lf-M9-cp2-13 视图组件

原文:https://www.cnblogs.com/wenyule/p/10434256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!