Django Rest Framework学习进程(三) 使用类视图来编写API
Hello大家好,已经到了第三部分了嘻嘻嘻,这部分主要是讲如何用类视图来写API,代码会越来越简洁的,大家加油
1.重构函数视图(APIView)
//重构根视图,需要继承APIView这个类,我们之前利用request.method来判断请求来源是什么样是请求,然而现在,我们只需要书写对应的函数就行,如:get函数用来处理get请求,post函数用来处理post请求等。 class SnippetList(APIView): """ 列出所有的snippets,或创建一个新的snippet """ def get(self,request,format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets,many=True) return Response(serializer.data) def post(self,request,format=None): serilizer = SnippetSerializer(data=request.data) if serilizer.is_valid(): serilizer.save() return Response(serilizer.data,status=status.HTTP_201_CREATED) return Response(serilizer.errors,status=status.HTTP_400_BAD_REQUEST) //重构实例视图,你会发现,重构完后的视图也变得简洁了 class SnippetDetail(APIView): """ 获取,更新或删除一个snippet """ def get_object(self,pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 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(): serializer.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)
2.URL的重写
//Django的类视图,需要在后面加上as_view() urlpatterns = [ url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) //到这里,启动项目可以发现和之前的一样
3.使用mixins类来重写视图
//到目前为止,我们使用的创建/获取/更新/删除操作和我们创建的任何基于模型的API视图非常相似,这些行为都是基于REST framework中的mixin类来实现的,接下来介绍如何使用mixins类来写视图 #首先导入以下依赖包 from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework import mixins from rest_framework import generics //重写SnippetList类视图,在这个mixins类视图中,我们使用GenericAPIView来构建视图,并加入了ListModelMixin and CreateModelMixin. //基类提供核心的功能,mixins类提供.list()和.create()方法 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) //重写SnippetDetail,在这个mixins类中加入了.retrieve() .update() .destroy()方法 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)
4.让视图变得更简洁
//通过使用mixins类,可以使我们的类视图变得更简洁,但其实还可以更简洁,因为REST框架已经提供了一组已经混合好的通用视图,使用它可以让代码更为简洁 //重写SnippetList和SnippetDetail,你会发现...这也太简洁了8..... //其实看继承的类的源码可以发现,这些继承的类都是用mixins类来实现的 class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer