1. 程式人生 > >django rest_framework(四)——APIVIEW

django rest_framework(四)——APIVIEW

elf del mark 操作 set true ask min exception

1.使用類視圖APIView重寫API
類視圖APIView,取代@api_view裝飾器,代碼如下:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

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


class SnippetList(APIView):
    def get(self, request):
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    def post(self, request):
        data = request.data
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class SnippetDetail(APIView):
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Exception as e:
            pass

    def get(self, request, pk):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

2.編輯urls.py

from django.conf.urls import url, include
from django.contrib import admin

from snippets import views

urlpatterns = [
    url(r‘^snippets/$‘, views.SnippetList.as_view()),
    url(r‘^snippets/(?P<pk>[0-9]+)/$‘, views.SnippetDetail.as_view()),
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘))
]

APIView視圖類,調用as_view()方法

3.使用Mixins
Mixins封裝了增刪改查的操作,因此可以使用Mixins簡化代碼,如下:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import mixins, generics

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


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)


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)

SnippetList繼承了mixins的ListModelMixin和CreateModelMixin類,
賦值queryset,serializer_class屬性,
然後定義了get,post方法,分別調用mixins的list,create函數。
SnippetDetail定義類似。

4.使用通用類視圖generics
rest_framework定義了可能的增刪改查組合,優化了多重繼承的繁雜

from rest_framework import generics

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


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


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

使用generics的ListCreateAPIView和RetrieveUpdateDestroyAPIView替代mixins類
同時,去掉了get,post方法

5.使用viewsets進一步簡化
viewsets包含了對一個model的增刪改查全部操作,代碼如下:

from rest_framework import viewsets

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


class SnippetViewSet(viewsets.ModelViewSet):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

django rest_framework(四)——APIVIEW