码迷,mamicode.com
首页 > Windows程序 > 详细

django rest_framework(四)——APIVIEW

时间:2018-09-06 16:15:26      阅读:479      评论:0      收藏:0      [点我收藏+]

标签:UNC   names   generics   model   djang   let   param   word   一个   

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

标签:UNC   names   generics   model   djang   let   param   word   一个   

原文地址:https://www.cnblogs.com/zamo-7/p/9598469.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!