• Django REST framework视图


     Django REST framework视图

    学习序列化的时候发现有大量的冗余代码,所以我们要使用Django REST framework里的视图减少我们的代码

    DRF中的request

    在Django REST Framework中内置的Request类扩展了Django中的Request类,实现了很多方便的功能--如请求数据解析和认证等。

    比如,区别于Django中的request从request.GET中获取URL参数,从request.POST中取某些情况下的POST数据。

    在APIView中封装的request,就实现了请求数据的解析:

    对于GET请求的参数我们通过request.query_params来获取。

    对于POST请求、PUT请求的数据我们通过request.data来获取。

    学习序列化时的部分

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from .models import *
    from django.shortcuts import HttpResponse
    from django.core import serializers
    
    
    from rest_framework import serializers
    
    
    class BookSerializers(serializers.ModelSerializer):
          class Meta:
              model=Book
              fields="__all__"
              #depth=1
    
    
    class PublshSerializers(serializers.ModelSerializer):
    
          class Meta:
              model=Publish
              fields="__all__"
              depth=1
    
    
    class BookViewSet(APIView):
    
        def get(self,request,*args,**kwargs):
            book_list=Book.objects.all()
            bs=BookSerializers(book_list,many=True,context={'request': request})
            return Response(bs.data)
    
    
        def post(self,request,*args,**kwargs):
            print(request.data)
            bs=BookSerializers(data=request.data,many=False)
            if bs.is_valid():
                print(bs.validated_data)
                bs.save()
                return Response(bs.data)
            else:
                return HttpResponse(bs.errors)
    
    
    class BookDetailViewSet(APIView):
    
        def get(self,request,pk):
            book_obj=Book.objects.filter(pk=pk).first()
            bs=BookSerializers(book_obj,context={'request': request})
            return Response(bs.data)
    
        def put(self,request,pk):
            book_obj=Book.objects.filter(pk=pk).first()
            bs=BookSerializers(book_obj,data=request.data,context={'request': request})
            if bs.is_valid():
                bs.save()
                return Response(bs.data)
            else:
                return HttpResponse(bs.errors)
    
    
    class PublishViewSet(APIView):
    
        def get(self,request,*args,**kwargs):
            publish_list=Publish.objects.all()
            bs=PublshSerializers(publish_list,many=True,context={'request': request})
            return Response(bs.data)
    
    
        def post(self,request,*args,**kwargs):
    
            bs=PublshSerializers(data=request.data,many=False)
            if bs.is_valid():
                # print(bs.validated_data)
                bs.save()
                return Response(bs.data)
            else:
                return HttpResponse(bs.errors)
    
    
    class PublishDetailViewSet(APIView):
    
        def get(self,request,pk):
    
            publish_obj=Publish.objects.filter(pk=pk).first()
            bs=PublshSerializers(publish_obj,context={'request': request})
            return Response(bs.data)
    
        def put(self,request,pk):
            publish_obj=Publish.objects.filter(pk=pk).first()
            bs=PublshSerializers(publish_obj,data=request.data,context={'request': request})
            if bs.is_valid():
                bs.save()
                return Response(bs.data)
            else:
                return HttpResponse(bs.errors)
    View Code

    mixin混合类编写视图

    from rest_framework import mixins
    from rest_framework import generics
    
    class BookViewSet(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      generics.GenericAPIView):
    
        queryset = 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 BookDetailViewSet(mixins.RetrieveModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        generics.GenericAPIView):
        queryset = 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)

    使用通用的基于类的视图

    通过使用mixin类,我们使用更少的代码重写了这些视图,但我们还可以再进一步。REST框架提供了一组已经混合好(mixed-in)的通用视图,我们可以使用它来简化我们的views.py模块。

    from rest_framework import mixins
    from rest_framework import generics
    
    class BookViewSet(generics.ListCreateAPIView):
    
        queryset = Book.objects.all()
        serializer_class = BookSerializers
    
    class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializers
    
    class PublishViewSet(generics.ListCreateAPIView):
    
        queryset = Publish.objects.all()
        serializer_class = PublshSerializers
    
    class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
        queryset = Publish.objects.all()
        serializer_class = PublshSerializers

    使用视图集

    只写一个视图类,那就需要改urls了,让他们都指向那一个类:

        url(r'^books/$', views.BookViewSet.as_view({
    "get":"list",
    "post":"create"
    }),name="book_list"), url(r'^books/(?P<pk>d+)$', views.BookViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }),name="book_detail"),

    views.py:

    from rest_framework import viewsets
    
    class BookViewSet(viewsets.ModelViewSet):
        queryset = Book.objects.all()
        serializer_class = BookSerializers

    高级路由

    捂脸表情,路由还能再简化一次

    from rest_framework.routers import DefaultRouter
    
    router = DefaultRouter()
    router.register(r'school', views.SchoolView)
    router.register(r'student', views.SchoolView)
    # 注册完后会帮你生成url只需要加入到url里
    urlpatterns += router.urls 或 url(r'', include(routers.urls))

    原理流程图

  • 相关阅读:
    sqlalchemy的orm的高级用法,分组,排序,聚合等方法
    flask的SQLAlchemy,连接数据库的增删改查操作
    wtforms的form表单的高级用法
    初始wtforms表单,以及简单使用
    命令启动flask以及自定义命令
    MySQL5.5安装教程
    Java设计模式-策略模式实际应用场景
    Java设计模式-策略模式详解
    Oracle数据库之FORALL与BULK COLLECT语句
    代理模式详解(静态代理和动态代理的区别以及联系)
  • 原文地址:https://www.cnblogs.com/lxfpy/p/10979929.html
Copyright © 2020-2023  润新知