转载自:http://www.django-rest-framework.org/tutorial/3-class-based-views/

Tutorial 3: Class-based Views

We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.

Rewriting our API using class-based views

We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of 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):
"""
List all snippets, or create a new 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):
serializer = SnippetSerializer(data=request.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)

So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in views.py.

class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
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)

That's looking good. Again, it's still pretty similar to the function based view right now.

We'll also need to refactor our urls.py slightly now that we're using class-based views.

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.SnippetDetail.as_view()),
] urlpatterns = format_suffix_patterns(urlpatterns)

Okay, we're done. If you run the development server everything should be working just as before.

Using mixins

One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.

The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.

Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module again.

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)

We'll take a moment to examine exactly what's happening here. We're building our view using GenericAPIView, and adding in ListModelMixin and CreateModelMixin.

The base class provides the core functionality, and the mixin classes provide the .list() and .create() actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough stuff so far.

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)

Pretty similar. Again we're using the GenericAPIView class to provide the core functionality, and adding in mixins to provide the .retrieve().update() and .destroy() actions.

Using generic class-based views

Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer

Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.

Tutorial 3: Class-based Views的更多相关文章

  1. A Complete Tutorial on Tree Based Modeling from Scratch (in R & Python)

    A Complete Tutorial on Tree Based Modeling from Scratch (in R & Python) MACHINE LEARNING PYTHON  ...

  2. Tutorial on GoogleNet based image classification --- focus on Inception module and save/load models

    Tutorial on GoogleNet based image classification  2018-06-26 15:50:29 本文旨在通过案例来学习 GoogleNet 及其 Incep ...

  3. [Angular Tutorial] 9 -Routing & Multiple Views

    在这一步中,您将学到如何创建一个布局模板,并且学习怎样使用一个叫做ngRoute的Angular模块来构建一个具有多重视图的应用. ·当您现在访问/index.html,您将被重定向到/index.h ...

  4. Tutorial 6: ViewSets & Routers

    转载自:http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/ Tutorial 6: ViewSets & ...

  5. Tutorial 2: Requests and Responses

    转载自:http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ Tutorial 2: Requests and ...

  6. Python Web框架(URL/VIEWS/ORM)

    一.路由系统URL1.普通URL对应 url(r'^login/',views.login) 2.正则匹配 url(r'^index-(\d+).html',views.index) url(r'^i ...

  7. Django restframwork教程之类视图(class-based views)

    我们也可以使用类的views写我们的API,我们将看到这是一个强大的模式,允许我们重用公共功能,让我们的代码整洁 使用Class-based Views重新改写我们的API 打开views.py文件, ...

  8. RESR API (三)之Views

    Class-based Views Django's class-based views are a welcome departure from the old-style views. - Rei ...

  9. Django之 Views组件

    本节内容 路由系统 models模型 admin views视图 template模板 我们已经学过了基本的view写法 单纯返回字符串 1 2 3 4 5 6 7 8 def current_dat ...

随机推荐

  1. 【刷题】BZOJ 4650 [Noi2016]优秀的拆分

    Description 如果一个字符串可以被拆分为 AABBAABB 的形式,其中 AA 和 BB 是任意非空字符串,则我们称该字符串的这种拆分是优秀的.例如,对于字符串 aabaabaa,如果令 A ...

  2. yii2框架-yii2局部关闭(开启)csrf的验证

    (1)全局使用,我们直接在配置文件中设置enableCookieValidation为true request => [ 'enableCookieValidation' => true, ...

  3. 扶苏的bitset浅谈

    bitset作为C++一个非常好用的STL,在一些题目中巧妙地使用会产生非常不错的效果.今天扶苏来分享一点bitset的基础语法和应用 本文同步发布于个人其他博客,同时作为P3674题解发布. 本文感 ...

  4. 在 Ubuntu16.04上安装anaconda+Spyder+TensorFlow(支持GPU)

    TensorFlow 官方文档中文版 http://www.tensorfly.cn/tfdoc/get_started/introduction.html https://zhyack.github ...

  5. Codeforces Round #301 (Div. 2)A B C D 水 模拟 bfs 概率dp

    A. Combination Lock time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  6. Ubuntu配置vncserver

    https://help.aliyun.com/knowledge_detail/59330.html 首先,安装桌面环境和vnc4server: sudo apt-get install gnome ...

  7. springMVC参数绑定与数据回显

    简单例子:修改商品信息的jsp页面: 参数绑定过程: 1.2.1  默认支持的参数类型 处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值. 1.1.1     HttpServletReq ...

  8. python自学笔记(二)

    通过前文介绍,大体上可以用学过的知识做一些东西了. 这里简单介绍下python参数解析argparse命令. 使用argparse需要引用  import argparse 然后调用 parser = ...

  9. 「Python」python-nmap安装与入门

    1.安装namp https://nmap.org/download.html 下载链接 PS:windows安装似乎麻烦一些,需要多下载npcap,官网有链接 2.python安装 注意,注意,注意 ...

  10. libxml2在mingw下编译

    1.配置MingW路径,在环境变量path中加入/mingw32/bin2.解压libxml,进入win32目录3.记事本打开configure.js,找到var compiler = "m ...