django rest framework我的學習筆記(五)————Tutorial3.Class-based Views

(官網地址)[django rest framework我的學習筆記(四)————Tutorial]python

Class-based views

咱們也可以使用class-based view 來編寫咱們的API views,而不是基於function based views.正如咱們所看到的,這是一個強大的模式,它使咱們的功能可以複用,並保持咱們的代碼整潔。django

使用class-based views重寫咱們的API

咱們開始重寫編寫咱們的root views。這一切都只涉及修改一點views.py文件。post

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.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,咱們完成了。rest

mixins

大量使用class-based views的好處之一,能夠讓咱們輕易的組成可複用的組件。
咱們須要使用的操做就 建立/檢索/更新/刪除。這些常見的行爲咱們能夠使用REST framework 的 mixin classes。
接下來將展現使用mixin classes來組成咱們的views。咱們再一次來到views.py文件。code

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.orm

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.ip

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
相關文章
相關標籤/搜索