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__"
|