介绍
该教程将会让你理解 REST 框架的各个组件是怎么工作的。
该教程很深入,你可能需要取饼干和你喜欢的饮料。如果你想快速的浏览,你应该去看 quickstart 。
注意:该教程对应的代码可以去GitHub看, tomchristie/rest-framework-tutorial 。完整的实现作为测试版本放在这里:available here.
建立一个新环境
在我们做之前,需要使用virtualenv建立一个新的虚拟环境。这将确保我们的包配置完好地与其他工程相隔离。
virtualenv env source env/bin/activate
现在我们在一个虚拟的环境,我们可以安装需要的包。
pip install django pip install djangorestframework pip install pygments # We'll be using this for the code highlighting 我们使用它让代码高亮。
注意:需要退出虚拟环境,只需键入deactivate。更多信息可以看这里:
virtualenv documentation
开始
好了,我们准备编写代码,建立一个新的工程
cd ~ django-admin.py startproject tutorial cd tutorial
一旦建立了工程,我们就要建立一个app用来建立一个简单的Web API。
python manage.py startapp snippets
The simplest way to get up and running will probably be to use an sqlite3
database for the tutorial. Edit the tutorial/settings.py
file, and set the default database "ENGINE"
to "sqlite3"
, and "NAME"
to "tmp.db"
.
要使用一个sqlite3数据库,最简单的方式就是在 tutorial/settings.py 文件中配置如下:
DATABASES ={'default':{'ENGINE':'django.db.backends.sqlite3','NAME':'tmp.db','USER':'','PASSWORD':'','HOST':'','PORT':'',}}
We'll also need to add our new snippets
app and the rest_framework
app to INSTALLED_APPS
.
我们还需要把 rest_framework 和在上面建立的新 app 添加进来。
INSTALLED_APPS =(...'rest_framework','snippets',)
We also need to wire up the root urlconf, in the tutorial/urls.py
file, to include our snippet app's URLs.
同样需要配置根 URL , 编辑 tutorial/urls.py 文件,把 snippet 的 URL 包含进来。
urlpatterns = patterns('', url(r'^', include('snippets.urls')),)
Creating a model to work with
建立一个数据库模型
For the purposes of this tutorial we're going to start by creating a simple Snippet
model that is used to store code snippets. Go ahead and edit the snippets
app's models.py
file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
为 app snippet 建立一个简单的数据库模型名为 Snippet,用来存储代码片段。在 snippets/models.py 中键入如下信息。
from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS =[item for item in get_all_lexers()if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
classMeta: ordering =('created',)
Don't forget to sync the database for the first time.
别忘了同步数据库。
python manage.py syncdb
Creating a Serializer class
建立一个序列化器 Serializer 类
The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as json
. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets
directory named serializers.py
and add the following.
我们需要为 Web API 提供序列化和逆序列化方法,用像 json 这样的数据格式来表现 snippet 数据模型。我们可以像Django的表单类那样来声明序列化器类。在 app snippets 目录下建立一个名为 serializers.py 的文件,在该文件中键入:
from django.forms import widgets from rest_framework import serializers from snippets.models importSnippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): pk = serializers.Field()# Note: `Field` is an untyped read-only field. title = serializers.CharField(required=False, max_length=100) code = serializers.CharField(widget=widgets.Textarea, max_length=100000) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def restore_object(self, attrs, instance=None):
""" Create or update a new snippet instance, given a dictionary of deserialized field values.
创建或者更新一个新的 snippet 实例,需要一个字典,该字典包含逆序列化域的值。 Note that if we don't define this method, then deserializing data will simply return a dictionary of items.
如果我们没有定义改方法,纳秒逆序列化数据只会简单地返回一个项目字典 """
if instance:# Update existing instance instance.title = attrs.get('title', instance.title) instance.code = attrs.get('code', instance.code) instance.linenos = attrs.get('linenos', instance.linenos) instance.language = attrs.get('language', instance.language) instance.style = attrs.get('style', instance.style)
return instance # Create new instancereturnSnippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The restore_object
method defines how fully fledged instances get created when deserializing data.
该序列化器类的第一部分定义了需要序列化和逆序列化的域。restore_object方法定义了怎样用逆序列化的数据来创建一个新的实例。
Notice that we can also use various attributes that would typically be used on form fields, such as widget=widgets.Textarea
. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
注意:我们同样可以使用其他更多的用在表单中的属性,像 widget=weidgets.Textarea。这些属性可以用来控制序列化器渲染一个 HTML 表单的行为,尤其对显示可浏览的 API 有用,这个我们会在后面的教程中看到。
We can actually also save ourselves some time by using the ModelSerializer
class, as we'll see later, but for now we'll keep our serializer definition explicit.
我们可以用ModelSerializer类来快速生成,但是现在我们会显示地定义序列化器。
Working with Serializers
序列化器是如何工作的
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
在进行进一步的工作之前,我们先熟悉我们的新的序列化器类。在shell键入:
python manage.py shell
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
创建一个snippets实例:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser snippet =Snippet(code='foo = "bar" ') snippet.save() snippet =Snippet(code='print "hello, world" ') snippet.save()
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
我们获得一些 snippet 实例,看看序列化其中一个的效果:
serializer =SnippetSerializer(snippet) serializer.data # {'pk': 2, 'title': u'', 'code': u'print "hello, world" ', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json
.
上面我们将 模型的实例转换成Python数据类型。我们用序列化器将其渲染成 json:
content =JSONRenderer().render(serializer.data) content # '{"pk": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into Python native datatypes...
逆序列化是类似的,首先我们解析数据流,将其转成Python数据类型。
# This import will use either `StringIO.StringIO` or `io.BytesIO`
# as appropriate, depending on if we're running Python 2 or Python 3.
from rest_framework.compat importBytesIO stream =BytesIO(content) data =JSONParser().parse(stream)
...then we restore those native datatypes into to a fully populated object instance.
然后存储Python数据类型到对象实例中去。
serializer =SnippetSerializer(data=data) serializer.is_valid()# True serializer.object # <Snippet: Snippet object>
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
注意这些API和django表单的相似处。这些相似点, 在我们讲述在view中使用serializers时将更加明显。
We can also serialize querysets instead of model instances. To do so we simply add a many=True
flag to the serializer arguments.
我么也可以序列化 querysets,只需要简单的加上 many = True。
serializer =SnippetSerializer(Snippet.objects.all(), many=True) serializer.data # [{'pk': 1, 'title': u'', 'code': u'foo = "bar" ', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world" ', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
Using ModelSerializers
使用模型序列化器
Our SnippetSerializer
class is replicating a lot of information that's also contained in the Snippet
model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both Form
classes and ModelForm
classes, REST framework includes both Serializer
classes, and ModelSerializer
classes.
Let's look at refactoring our serializer using the ModelSerializer
class. Open the file snippets/serializers.py
again, and edit the SnippetSerializer
class.
上面的 SnipperSerializer 类有很多在Snippet 模型中的重复信息,如果我们能够去掉重复代码就相当不错。
类似与django提供Form类和ModelForm类,Rest Framework也包含了Serializer 类和 ModelSerializer类。
我们看看使用ModelSerializer类重构后的序列化器,编辑snippets/serializers.py如下:
class SnippetSerializer(serializers.ModelSerializer):
class Meta: model =Snippet fields =('id','title','code','linenos','language','style')
Writing regular Django views using our Serializer
用序列化器编写原生的Django视图函数
Let's see how we can write some API views using our new Serializer class. For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
让我们看看通过 Serializer 类怎样来编写 API 的视图函数,现在我们不会使用 REST 框架中的特性,仅仅写原生的Django视图函数。
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into json
.
我们创建一个 HttpResponse 的子类,用来将任何数据转换成 JSON格式
Edit the snippets/views.py
file, and add the following.
编辑snippets/views.py,如下:
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data,**kwargs): content =JSONRenderer().render(data) kwargs['content_type']='application/json' super(JSONResponse, self).__init__(content,**kwargs)
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
我们API的目的是,可以通过view来列举全部的Snippet的内容,或者创建一个新的snippet
@csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method =='GET': snippets =Snippet.objects.all() serializer =SnippetSerializer(snippets,many=True)
return JSONResponse(serializer.data) elif request.method =='POST': data =JSONParser().parse(request) serializer =SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt
. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
注意,因为我们要通过client向该view post一个请求,所以我们要将该view 标注为csrf_exempt, 以说明不是一个CSRF事件。它不同于以往的正常的视图函数,REST框架的视图函数事实上使用更加敏感的行为,它现在只是为了达到我们的目的。
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
我们还要一个视图函数来为单独的 snipet 实例服务,用来恢复,更新和删除 snippet
@csrf_exempt def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet =Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method =='GET': serializer = SnippetSerializer(snippet) return JSONResponse(serializer.data) elif request.method =='PUT': data =JSONParser().parse(request) serializer =SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method =='DELETE': snippet.delete() return HttpResponse(status=204)
Finally we need to wire these views up. Create the snippets/urls.py
file:
将views.py保存,在Snippets目录下面创建urls.py,添加以下内容:
from django.conf.urls import patterns, url urlpatterns = patterns('snippets.views', url(r'^snippets/$','snippet_list'), url(r'^snippets/(?P<pk>[0-9]+)/$','snippet_detail'),
)
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed json
, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
注意我们有些边缘事件没有处理,服务器可能会抛出500异常。
Testing our first attempt at a Web API
测试我们第一次的 API
Now we can start up a sample server that serves our snippets.
现在我们启动server来测试我们的Snippet。
在python mange.py shell终端下执行(如果前面进入还没有退出)
>>quit()
>>python manage.py runserver
Validating models...0 errors found
Django version 1.4.3, using settings 'tutorial.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In another terminal window, we can test the server.
在另一个终端窗口,我们可以测试服务
We can get a list of all of the snippets.
curl http://127.0.0.1:8000/snippets/
[
{"id":1,"title":"","code":"foo = "bar" ","linenos": false,"language":"python","style":"friendly"},
{"id":2,"title":"","code":"print "hello, world" ","linenos": false,"language":"python","style":"friendly"}
]
Or we can get a particular snippet by referencing its id.
或者我们通过snippet id来获取一个snippet实例:
curl http://127.0.0.1:8000/snippets/2/ {"id":2,"title":"","code":"print "hello, world" ","linenos": false,"language":"python","style":"friendly"}
Similarly, you can have the same json displayed by visiting these URLs in a web browser.
类似地,你也可以通过浏览器访问 URL 来获取 json。
Where are we now
We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
到目前位置,我们获得了一个用来序列化模型的 API 非常类似Django的Forms, 使用原生的Django视图函数来写API的视图函数。
Our API views don't do anything particularly special at the moment, beyond serving json
responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
我们的 API 视图函数没有做其他事情,只是返回JSON数据,而且还有一些边缘事件没有清理,但是它已经是一个可用的 API 了。