Django REST framework 是用于构建Web API 的强大而灵活的工具包。python
咱们可能想使用REST框架的一些缘由:git
REST framework is a collaboratively(合做地) funded project(基金项目). If you use REST framework commercially we strongly encourage you to invest(投资) in its continued development(可持续发展) by signing up for a paid plan.(注册付费计划)github
Every single sign-up helps us make REST framework long-term financially sustainable(财务上可持续发展)数据库
Many thanks to all our wonderful sponsors(赞助商), and in particular to our premium backers(优质的支持者), Rover, Sentry, Stream, Machinalis, and Rollbar.django
REST framework requires the following:api
The following packages are optional:markdown
如下软件包是可选的:app
Install using pip
, including any optional packages you want...框架
1
2
3
|
pip install djangorestframework
pip install markdown
# Markdown support for the browsable API.
pip install django
-
filter
# Filtering support
|
...or clone the project from github.ide
1
|
git clone git@github.com:encode
/
django
-
rest
-
framework.git
|
Add 'rest_framework'
to your INSTALLED_APPS
setting.(记得在setting文件里面添加rest_framework,固然,你还得先安装djangorestframework)
1
2
3
4
|
INSTALLED_APPS
=
(
...
'rest_framework'
,
)
|
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py
file.
若是您打算使用可浏览的API,您可能还须要添加REST框架的登陆和注销视图。将如下内容添加到您的根urls.py
文件中。
1
2
3
4
|
urlpatterns
=
[
...
url(r
'^api-auth/'
, include(
'rest_framework.urls'
, namespace
=
'rest_framework'
))
]
|
Note that the URL path can be whatever you want, but you must include 'rest_framework.urls'
with the 'rest_framework'
namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
请注意,URL路径能够是任何你想要的,但你必须包括'rest_framework.urls'
与'rest_framework'
命名空间。您能够在Django 1.9+中省略命名空间,REST框架将为您设置。
Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.
说了一堆,直接来个demo,快速上手,看看效果。官网请看:http://www.django-rest-framework.org/tutorial/quickstart/
首先确定得先建立django程序啦,接着建立APP,这里我建立了一个quickstart的app。
Now sync your database for the first time:同步数据库
1
|
python manage.py migrate
|
建立超级用户用于登录。We'll also create an initial user named admin
with a password of password123
. We'll authenticate as that user later in our example.
1
|
python manage.py createsuperuser
|
首先咱们要定义一些序列化程序。在quickstart这个APP下建立serializers文件,用于展现数据。
First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py
that we'll use for our data representations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from
django.contrib.auth.models
import
User, Group
from
rest_framework
import
serializers
class
UserSerializer(serializers.HyperlinkedModelSerializer):
class
Meta:
model
=
User
fields
=
(
'url'
,
'username'
,
'email'
,
'groups'
)
class
GroupSerializer(serializers.HyperlinkedModelSerializer):
class
Meta:
model
=
Group
fields
=
(
'url'
,
'name'
)
|
Notice that we're using hyperlinked relations in this case, with HyperlinkedModelSerializer
. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
请注意,在这种状况下,咱们正在使用超连接关系HyperlinkedModelSerializer
。您还可使用主键和各类其余关系,但超连接是好的RESTful设计。
Right, we'd better write some views then. Open tutorial/quickstart/views.py
and get typing. 写一些视图,查询数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
from
django.contrib.auth.models
import
User, Group
from
rest_framework
import
viewsets
from
tutorial.quickstart.serializers
import
UserSerializer, GroupSerializer
class
UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset
=
User.objects.
all
().order_by(
'-date_joined'
)
serializer_class
=
UserSerializer
class
GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset
=
Group.objects.
all
()
serializer_class
=
GroupSerializer
|
Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets
.
We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
咱们不是编写多个视图,而是将全部常见的行为组合到一个名为viewset的类中。
若是须要的话,咱们能够很容易地将它们分解为单独的视图,可是使用viewset使视图逻辑组织得很好,而且很是简洁。
Okay, now let's wire up the API URLs. On to tutorial/urls.py
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from
django.conf.urls
import
url, include
from
rest_framework
import
routers
from
tutorial.quickstart
import
views
<br>
router
=
routers.DefaultRouter()
router.register(r
'users'
, views.UserViewSet)
router.register(r
'groups'
, views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns
=
[
url(r
'^'
, include(router.urls)),
url(r
'^api-auth/'
, include(
'rest_framework.urls'
, namespace
=
'rest_framework'
))
]
|
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
咱们能够经过简单地使用路由器类注册该视图来自动生成API的URL conf。
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
再次,若是咱们须要对API URL的更多控制,咱们能够简单地将其下拉到使用常规的基于类的视图,并明确地编写URL conf。
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
最后,咱们将包括默认登陆和注销视图,以便与可浏览的API一块儿使用。这是可选的,但若是您的API须要身份验证,而且您想要使用可浏览的API,那么这是很是有用的。
We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in tutorial/settings.py
咱们也想设置一些全局设置。咱们想打开分页,咱们但愿咱们的API只能由管理员使用
1
2
3
4
5
6
7
8
9
10
11
|
INSTALLED_APPS
=
(
...
'rest_framework'
,
)
REST_FRAMEWORK
=
{
'DEFAULT_PERMISSION_CLASSES'
: [
'rest_framework.permissions.IsAdminUser'
,
],
'PAGE_SIZE'
:
10
}
|
Okay, we're done.
主界面,好像啥也没有……
用超级用户登录后的界面。
有增删改查的功能。
接下来了解下rest framework 的全部组件,而且得知它们是如何组合在一块儿的,这是很是值得去学习的。
Serialization 序列化
这里呢,不对普通的序列化做介绍。接下来咱们使用下 ModelSerializers model序列化让咱们写的代码更少,更简介。Django提供了form和modelform同样,REST框架包括了序列化器类和模型序列化器类。
例如 models 文件中有一个关于文章的表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class
Article(models.Model):
"""文章资讯"""
title
=
models.CharField(max_length
=
255
, unique
=
True
, db_index
=
True
, verbose_name
=
"标题"
)
source
=
models.ForeignKey(
"ArticleSource"
, verbose_name
=
"来源"
)
article_type_choices
=
((
0
,
'资讯'
), (
1
,
'视频'
))
article_type
=
models.SmallIntegerField(choices
=
article_type_choices, default
=
0
)
brief
=
models.TextField(max_length
=
512
, verbose_name
=
"摘要"
)
head_img
=
models.CharField(max_length
=
255
)
content
=
models.TextField(verbose_name
=
"文章正文"
)
pub_date
=
models.DateTimeField(verbose_name
=
"上架日期"
)
offline_date
=
models.DateTimeField(verbose_name
=
"下架日期"
)
status_choices
=
((
0
,
'在线'
), (
1
,
'下线'
))
status
=
models.SmallIntegerField(choices
=
status_choices, default
=
0
, verbose_name
=
"状态"
)
order
=
models.SmallIntegerField(default
=
0
, verbose_name
=
"权重"
, help_text
=
"文章想置顶,能够把数字调大"
)
comment_num
=
models.SmallIntegerField(default
=
0
, verbose_name
=
"评论数"
)
agree_num
=
models.SmallIntegerField(default
=
0
, verbose_name
=
"点赞数"
)
view_num
=
models.SmallIntegerField(default
=
0
, verbose_name
=
"观看数"
)
collect_num
=
models.SmallIntegerField(default
=
0
, verbose_name
=
"收藏数"
)
tags
=
models.ManyToManyField(
"Tags"
, blank
=
True
, verbose_name
=
"标签"
)
date
=
models.DateTimeField(auto_now_add
=
True
, verbose_name
=
"建立日期"
)
def
__str__(
self
):
return
"%s-%s"
%
(
self
.source,
self
.title)
|
接下来,只须要写一个序列化器,即可以轻松对数据的进行获取,并且代码看起来特别简洁。
1
2
3
4
5
6
7
8
9
10
11
12
|
# 在 serilallzer.py 文件能够这样写
# 若是想使用哪一个model进行序列化,照此类推便可
# fields 若是想要获取全部字段, 使用"__all__"
# fields 若是只是想要获取一部分数据呢, 那么在 fields 中加入所序列化的model的字段便可
from
rest_framework.serializers
import
ModelSerializer
class
ArticleSerializer(ModelSerializer):
class
Meta:
model
=
models.Article
fields
=
(
"id"
,
"title"
,
"article_type"
,
"content"
, )
or
"__all__"
|