Tutorial 3: Class-based Views
转载自: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的更多相关文章
- 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 ...
- 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 ...
- [Angular Tutorial] 9 -Routing & Multiple Views
在这一步中,您将学到如何创建一个布局模板,并且学习怎样使用一个叫做ngRoute的Angular模块来构建一个具有多重视图的应用. ·当您现在访问/index.html,您将被重定向到/index.h ...
- Tutorial 6: ViewSets & Routers
转载自:http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/ Tutorial 6: ViewSets & ...
- Tutorial 2: Requests and Responses
转载自:http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ Tutorial 2: Requests and ...
- Python Web框架(URL/VIEWS/ORM)
一.路由系统URL1.普通URL对应 url(r'^login/',views.login) 2.正则匹配 url(r'^index-(\d+).html',views.index) url(r'^i ...
- Django restframwork教程之类视图(class-based views)
我们也可以使用类的views写我们的API,我们将看到这是一个强大的模式,允许我们重用公共功能,让我们的代码整洁 使用Class-based Views重新改写我们的API 打开views.py文件, ...
- RESR API (三)之Views
Class-based Views Django's class-based views are a welcome departure from the old-style views. - Rei ...
- Django之 Views组件
本节内容 路由系统 models模型 admin views视图 template模板 我们已经学过了基本的view写法 单纯返回字符串 1 2 3 4 5 6 7 8 def current_dat ...
随机推荐
- 【三】shiro入门 之 Realm
Realm:域,Shiro 从从Realm获取安全数据(如用户.角色.权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法:也 ...
- (转)REST无状态的理解
转至http://lelglin.iteye.com/blog/1852092 Representational State Transfer的缩写.我对这个词组的翻译是"表现层状态转化&q ...
- (转)Spring用代码来读取properties文件
转至http://www.cnblogs.com/Gyoung/p/5507063.html 我们都知道,Spring可以@Value的方式读取properties中的值,只需要在配置文件中配置org ...
- python中括号的使用
1. 列表list是用[ ]包住的以逗号分隔的数据集合 所有对列表的解析均采用[ ],不论是元素引用或取值 [ ]表示空列表 2. 字典由键-值(key-value)对构成,一般可采用{ }表示 取字 ...
- Openssl的编译安装以及Vs2012上环境搭建教程
Openssl的编译安装以及Vs2012上环境搭建教程 一.Openssl的编译安装 一.准备工作 1.Openssl下载地址:https://www.openssl.org/source/ 2.Ac ...
- 洛谷 P3338 [ZJOI2014]力 解题报告
P3338 [ZJOI2014]力 题目描述 给出n个数qi,给出Fj的定义如下: \(F_j = \sum_{i<j}\frac{q_i q_j}{(i-j)^2 }-\sum_{i>j ...
- 《剑指offer》— JavaScript(8)跳台阶
跳台阶 题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法. 实现代码 function jumpFloor(number) { if (number& ...
- winform登录代码
Program.cs文件中 static class Program { /// <summary> /// 应用程序的主入口点. /// </summary> [STAThr ...
- joomla! 3.X 开发系列教程
http://www.mengyunzhi.com/members-resource/joomla/87-joomla-menu-study.html 学习地址 http://blog.csdn.ne ...
- sloop公共程序之初始过程及启动
1:sloop_init() 初始化主要是初始化静态sloop_*** 结构体和填充struct sloop_data 结构体中的成员. //初始化静态存储区给sloop_***结构体 static ...