• rest-framework之视图


    一 基本视图

    二 mixin类和generice类编写视图

    三 使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView

    四 使用ModelViewSet

    ###

    一 基本视图

    写一个出版社的增删查改resful接口

    路由:

        url(r'^publish/$', views.PublishView.as_view()),
        url(r'^publish/(?P<pk>d+)/$', views.PublishDetailView.as_view()),

    视图:

    复制代码
    class PublishSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Publish
            fields='__all__'
    
    class PublishView(APIView):
    
        def get(self, request):
            publish_list = models.Publish.objects.all()
            bs = PublishSerializers(publish_list, many=True)
            # 序列化数据
    
            return Response(bs.data)
    
        def post(self, request):
            # 添加一条数据
            print(request.data)
    
            bs=PublishSerializers(data=request.data)
            if bs.is_valid():
                bs.save()  # 生成记录
                return Response(bs.data)
            else:
    
                return Response(bs.errors)
    
    class PublishDetailView(APIView):
        def get(self,request,pk):
            publish_obj=models.Publish.objects.filter(pk=pk).first()
            bs=PublishSerializers(publish_obj,many=False)
            return Response(bs.data)
        def put(self,request,pk):
            publish_obj = models.Publish.objects.filter(pk=pk).first()
    
            bs=PublishSerializers(data=request.data,instance=publish_obj)
            if bs.is_valid():
                bs.save() # update
                return Response(bs.data)
            else:
                return Response(bs.errors)
        def delete(self,request,pk):
            models.Publish.objects.filter(pk=pk).delete()
    
            return Response("")
    复制代码

    二 mixin类和generice类编写视图

    复制代码
    from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
    from rest_framework.generics import GenericAPIView
    class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    
        def get(self, request):
            return self.list(request)
    
        def post(self, request):
            return self.create(request)
    
    class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
        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)
    复制代码

    三 使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView

    复制代码
    from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
    class PublishView(ListCreateAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    
    class PublishDetailView(RetrieveUpdateDestroyAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    复制代码

    四 使用ModelViewSet

    路由:

        url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})),
        url(r'^publish/(?P<pk>d+)/$', views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),

    视图:

    from rest_framework.viewsets import ModelViewSet
    class PublishView(ModelViewSet):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers

    ###

    publish 5个接口 4中方式 3种路由

    路由

    from django.conf.urls import url,include
    from django.contrib import admin
    from api import views
    
    from rest_framework import routers
    router=routers.DefaultRouter()
    # 两个参数,一个是匹配的路由,一个是视图中写的CBV的类
    router.register('publish',views.PublishView)
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
    
        # publish之第一二三种(自定义路由)
        # url(r'^publish/$', views.PublishView.as_view()),
        # url(r'^publish/(?P<pk>d+)/$', views.PublishDetailView.as_view()),
        # publish之第四种 #(半自动路由(视图类继承ModelViewSet))
        # url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})),
        # url(r'^publish/(?P<pk>d+)/$', views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
        # url(r'',include(router.urls))  #(全自动路由(视图类继承ModelViewSet))
    
    ]
    View Code

    视图

    # Publish之第一种
    from api import models
    from rest_framework.views import APIView
    from rest_framework import serializers
    from rest_framework.response import Response
    
    class PublishSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Publish
            fields='__all__'
    
    class PublishView(APIView):
        def get(self, request):
            Publish_list = models.Publish.objects.all()
            bs = PublishSerializers(Publish_list, many=True)
            return Response(bs.data)
        def post(self, request):
            bs=PublishSerializers(data=request.data)
            if bs.is_valid():
                bs.save()  # 生成记录
                return Response(bs.data)
            else:
                return Response(bs.errors)
    
    class PublishDetailView(APIView):
        def get(self,request,pk):
            Publish_obj=models.Publish.objects.filter(pk=pk).first()
            bs=PublishSerializers(Publish_obj,many=False)
            return Response(bs.data)
        def put(self,request,pk):
            Publish_obj = models.Publish.objects.filter(pk=pk).first()
            bs=PublishSerializers(data=request.data,instance=Publish_obj)
            if bs.is_valid():
                bs.save() # update
                return Response(bs.data)
            else:
                return Response(bs.errors)
        def delete(self,request,pk):
            models.Publish.objects.filter(pk=pk).delete()
            return Response("删除成功")
    
    # Publish之第二种
    from api import models
    from rest_framework import serializers
    from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
    from rest_framework.generics import GenericAPIView
    
    class PublishSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Publish
            fields='__all__'
    
    class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    
        def get(self, request):
            return self.list(request)
    
        def post(self, request):
            return self.create(request)
    
    class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
        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)
            
    
    # Publish之第三种
    from api import models
    from rest_framework import serializers
    from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
    
    class PublishSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Publish
            fields='__all__'
    
    class PublishView(ListCreateAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    
    class PublishDetailView(RetrieveUpdateDestroyAPIView):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers        
        
        
    # Publish之第四种
    from api import models
    from rest_framework import serializers
    from rest_framework.viewsets import ModelViewSet
    
    class PublishSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Publish
            fields='__all__'
    
    class PublishView(ModelViewSet):
        queryset=models.Publish.objects.all()
        serializer_class=PublishSerializers
    View Code

    book 5个接口 4中方式 2种路由

    路由

        # book之第一二三种
        url(r'^book/$', views.BookView.as_view()),
        url(r'^book/(?P<pk>d+)/$', views.BookDetailView.as_view()),
        # book之第四种
        # url(r'^book/$', views.BookView.as_view({'get':'list','post':'create'})),
        # url(r'^book/(?P<pk>d+)/$', views.BookView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
    View Code

    视图

    # book之第一二三种
    # url(r'^book/$', views.BookView.as_view()),
    # url(r'^book/(?P<pk>d+)/$', views.BookDetailView.as_view()),
    # book之第四种
    # url(r'^book/$', views.BookView.as_view({'get':'list','post':'create'})),
    # url(r'^book/(?P<pk>d+)/$', views.BookView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
    
    # book之第一种
    from api import models
    from rest_framework.views import APIView
    from rest_framework import serializers
    from rest_framework.response import Response
    
    # class AuthorSerializer(serializers.ModelSerializer):
    #     class Meta:
    #         model=models.Author
    #         fields='__all__'
    
    class BookSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Book
            fields='__all__'
        # publish = serializers.SerializerMethodField()
        # def get_publish(self, obj):
        #     return obj.publish.name
        # authors = serializers.SerializerMethodField()
        # def get_authors(self, obj):
        #     ret = obj.authors.all()
        #     ss = AuthorSerializer(ret, many=True)
        #     return ss.data
    
    class BookView(APIView):
        def get(self, request):
            Book_list = models.Book.objects.all()
            Books_json = BookSerializers(Book_list, many=True)
            return Response(Books_json.data)
        def post(self, request):
            Book_json=BookSerializers(data=request.data)
            if Book_json.is_valid():
                Book_json.save()
                return Response(Book_json.data)
            else:
                return Response(Book_json.errors)
    
    class BookDetailView(APIView):
        def get(self,request,pk):
            Book_obj=models.Book.objects.filter(pk=pk).first()
            Book_json=BookSerializers(Book_obj,many=False)
            return Response(Book_json.data)
        def put(self,request,pk):
            Book_obj = models.Book.objects.filter(pk=pk).first()
            Book_json=BookSerializers(data=request.data,instance=Book_obj)
            if Book_json.is_valid():
                Book_json.save() # update
                return Response(Book_json.data)
            else:
                return Response(Book_json.errors)
        def delete(self,request,pk):
            models.Book.objects.filter(pk=pk).delete()
            return Response("删除成功")
            
            
    # book之第二种
    from api import models
    from rest_framework import serializers
    from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
    from rest_framework.generics import GenericAPIView
    
    class BookSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Book
            fields='__all__'
    
    class BookView(ListModelMixin,CreateModelMixin,GenericAPIView):
        queryset=models.Book.objects.all()
        serializer_class=BookSerializers
    
        def get(self, request):
            return self.list(request)
    
        def post(self, request):
            return self.create(request)
    
    class BookDetailView(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)
            
    
    # Book之第三种
    from api import models
    from rest_framework import serializers
    from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
    
    class BookSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Book
            fields='__all__'
    
    class BookView(ListCreateAPIView):
        queryset=models.Book.objects.all()
        serializer_class=BookSerializers
    
    class BookDetailView(RetrieveUpdateDestroyAPIView):
        queryset=models.Book.objects.all()
        serializer_class=BookSerializers
        
        
    # Book之第四种
    from api import models
    from rest_framework import serializers
    from rest_framework.viewsets import ModelViewSet
    
    class BookSerializers(serializers.ModelSerializer):
        class Meta:
            model=models.Book
            fields='__all__'
    
    class BookView(ModelViewSet):
        queryset=models.Book.objects.all()
        serializer_class=BookSerializers
    View Code

    ###

  • 相关阅读:
    java将Thu Jun 11 00:00:00 CST 2020类型转换为正常的时间类型
    SSM中JSP和thymeleaf同时使用
    java中thymeleaf获取项目根路径
    使用position:fixed定位的DIV元素,如何使其居中
    HTML设置textarea不可拖动
    使用js让Html页面弹出小窗口
    wow.js – 让页面滚动更有趣,使用方法
    CSS修改文本框placeholder提示的文字颜色
    JS监听用户按下ESC
    当div内所有元素都是浮动的时候,让容器(div)自动适应高度
  • 原文地址:https://www.cnblogs.com/xujinjin18/p/9790933.html
Copyright © 2020-2023  润新知