django rest framework个人学习笔记(五)————Tutorial3.Class-based Views

(官网地址)[django rest framework个人学习笔记(四)————Tutorial]

Class-based views

我们也能够使用class-based view 来编写我们的API views,而不是基于function based views.正如我们所看到的,这是一个强大的模式,它使我们的功能能够复用,并保持我们的代码整洁。

使用class-based views重写我们的API

我们开始重写编写我们的root views。这一切都只涉及修改一点views.py文件。

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class SnippetList(APIView):
"""
列出所有的snippet,或者创建一个新的snippet.
"""
    def get(self,request,format=None):
        snippet = Snippet.objects.all()
        serializer = SnippetSerializer(snippets,many=True)
        return Response(serializer.data)
        
    def post(self,request,format=None):
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.error,status=status.HTTP_400_BAD_REQUEST)

它看起来和之前的实例相当的类似,但是我们更好的将不同的HTTP请求分离了。
我们也能够更新我们的实例,在views.py文件中。

class SnippetDetail(APIView):
    """
    检索,更新或者删除一个snippet 实例。
    """
    def get_object(self,pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            return Hppt404
    
    
    def get(self,request,pk,format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)
        
    def put(self,request,pk,format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet,data=request.data)
        if serializer.is_valid():
            serlalizer.save()
            return Response(serializer.data)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
        
    def delete(self,request,pk,format=None)
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

我们还需要为我们的calss-based views添加url.

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r'^snippets/$',views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+/$',views.SnippetDatail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

Ok,我们完成了。

mixins

大量使用class-based views的好处之一,可以让我们轻易的组成可复用的组件。
我们需要使用的操作就 创建/检索/更新/删除。这些常见的行为我们可以使用REST framework 的 mixin classes。
接下来将展示使用mixin classes来组成我们的views。我们再一次来到views.py文件。

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics

class SnippetList(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    
    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)
    
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

来看看发生了什么,我们使用GenericAPIView来构建我们的view,并添加了ListModelMixinCreateModelMixin.
这个base class 包含了核心功能,mixin classes包含了.list().create()行为。我们能够使用这些行为来构建getpost.

class SnippetDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,                    
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
                    
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    
    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)

使用generic class-based views

使用mixin classes来重写我们的代码,比之前要稍微少写一些,但是我们想更进一步。REST framework 提供了mixed-in generic views,我们能够使用它来装饰我们的views.

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer = SnippetSerializer

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = snippet.objects.all()
    serializer = SnippetSerializer
    原文作者:張怼怼
    原文地址: https://segmentfault.com/a/1190000011127782
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞