其他分享
首页 > 其他分享> > 二个视图基类、五个视图扩展类、九个视图子类、视图集

二个视图基类、五个视图扩展类、九个视图子类、视图集

作者:互联网

使用APIView写5个接口

class BookView(APIView):
    renderer_classes = [JSONRenderer, ]

    def get(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(instance=book_list, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'})
        return Response({'code': 101, 'msg': '新增失败', 'err': ser.errors})


class BookDetailView(APIView):

    def get(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(book)
        return Response(ser.data)

    parser_classes = [JSONParser, ]

    def put(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功'})
        return Response({'code': 101, 'msg': '修改失败', 'err': ser.errors})

    def delete(self, request, pk):
        Book.objects.filter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})

继承GenericAPIView写5个接口


from rest_framework.generics import GenericAPIView

class PublishView(GenericAPIView): queryset = Publish.objects.all() serializer_class = PublishSerializer def get(self, request): model_list = self.get_queryset() ser = self.get_serializer(instance=model_list, many=True) return Response(ser.data) def post(self, request): ser = self.get_serializer(data=request.data) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '添加成功'}) return Response({'code': 101, 'msg': '添加失败', 'err': ser.errors}) class PublishDetailView(GenericAPIView): queryset = Publish.objects.all() serializer_class = PublishSerializer def get(self, request, *args, **kwargs): model_obj = self.get_object() ser = self.get_serializer(model_obj) return Response(ser.data) def put(self, request, *args, **kwargs): model_obj = self.get_object() ser = self.get_serializer(model_obj, data=request.data) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '修改成功'}) return Response({'code': 101, 'msg': '修改失败', 'err': ser.errors}) def delete(self, request, *args, **kwargs): self.get_object().delete() return Response({'code': 100, 'mag': '删除成功'})

5个视图扩展类

# 视图扩展类---》不是视图类---》没有继承视图类(View,APIView...子类)
ListModelMixin,  #获取所有
CreateModelMixin,#创建一个
RetrieveModelMixin,#查询一个
UpdateModelMixin,#更新一个
DestroyModelMixin#删除一个


from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin

class PublishView(GenericAPIView,ListModelMixin, CreateModelMixin,):
queryset = Publish.objects.all()
serializer_class = PublishSerializer

def get(self, request):
return super().list(request)

def post(self, request):
return super().create(request)


class PublishDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
def get(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)

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

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

9个视图子类

from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView, RetrieveAPIView, UpdateAPIView, \
    DestroyAPIView, RetrieveUpdateDestroyAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView

class PublishView(ListCreateAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer
    

class PublishDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

视图集

class PublishView(ModelViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

路由
    path('publish/', views.PublishView.as_view({'get':'list', 'post':'create'})),
    path('publish/<int:pk>', views.PublishView.as_view({'get':'retrieve','delete':'destroy','put':'update'})),


ModelViewSet=
# 5个视图扩展类---》每个类里有一个方法 list,create,retrieve,destory,update
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
# ViewSetMixin:特点,只要继承它,路由写法变了,变成了:as_view({'get': 'list', 'post': 'create'}---》请求方式和方法的对应关系
# generics.GenericAPIView 2个视图基类中得一个
GenericViewSet
-ViewSetMixin+GenericAPIView


# ViewSetMixin 源码分析
class ViewSetMixin:
@classonlymethod
def as_view(cls, actions=None, **initkwargs):
# actions={'get': 'list', 'post': 'create'}
def view(request, *args, **kwargs):
# method:get action:list
for method, action in actions.items():
# handler就是list
handler = getattr(self, action) #视图类反射有没有list
# 反射:把get变成了list
setattr(self, method, handler)
return self.dispatch(request, *args, **kwargs)
return csrf_exempt(view)
# 如果请求来了,会执行 view(request)

# 视图集中的类
    -ModelViewSet
    -ReadOnlyModelViewSet
    -ViewSetMixin
    -ViewSet   :ViewSetMixin+APIView
    -GenericViewSet:ViewSetMixin+GenericAPIView
    
# 以后你想继承APIView,但是路由想自动生成,继承ViewSet
# 以后想继承GenericViewSet,但是路由想自动生成,GenericViewSet

路由组件

# 1 继承了ViewSetMixin及其子类,路由写法变了
    -写法一:path('publish', views.PublishView.as_view({'get': 'lqz','post':'login'})),
    -写法二:自动生成
    # 第一步:导入一个路由类
    from rest_framework.routers import SimpleRouter, DefaultRouter

    # 第二步:实例化得到对象
    router=SimpleRouter()
    # router = DefaultRouter()  # 它会给每个注册的视图类都生成一个根路由
    # 第三步:注册路由---》使用视图类注册---》能自动生成路由
    router.register('books', views.BookView, 'books')
    router.register('publish', views.PublishView, 'publish')
    # 第四步:在总路由中注册  方式二
    path('', include(router.urls)),
    # 第四步:在总路由中注册  方式一
    # urlpatterns+=router.urls
    
    
# action装饰器的用法
    -之前自动生成路由只能生成
    {'get': 'list', 'post': 'create'},{'get': 'retrieve', 'put': 'update', 'delete': 'destroy'}
    -使用action装饰器来做对应关系
        '''
        methods:请求方式
        detail:
            False:是不是带id的路由  http://127.0.0.1/publish/3   http://127.0.0.1/publish
            True: 生成的路由publish/pk/lqz/
        url_path:如果不写,就是函数名生成的路径是:http://127.0.0.1/publish/lqz
        url_name:别名
        '''
  
    

路由

path('publish', views.PublishView.as_view({'get': 'lqz','post':'login'})),

视图类

class PublishView(ViewSetMixin,APIView):  # 路由写法变了,变成映射关系了,在视图类中可以写任意的方法名
    def lqz(self,request):
        return Response('lqz')
    def login(self,request):
        return Response('login')

 

 

 

BookView

标签:return,ser,get,子类,self,request,视图,基类,def
来源: https://www.cnblogs.com/wcc98/p/16390452.html