django rest framework 詳解


Django REST framework 是用於構建Web API 的強大而靈活的工具包。

我們可能想使用REST框架的一些原因:

  • Web瀏覽API對於開發人員來說是一個巨大的可用性。
  • 認證策略包括OAuth1a和OAuth2的包。
  • 支持ORM和非ORM數據源的序列化。
  • 如果你不需要更強大的功能,就可以使用常規的基於功能的視圖。
  • 廣泛的文檔和良好的社區支持。
  • 包括Mozilla、Red Hat、Heroku和Eventbrite在內的國際知名公司使用和信任。

 

Funding

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.(注冊付費計划)

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(優質的支持者), RoverSentryStreamMachinalis, and Rollbar.

 

Requirements

REST framework requires the following:

  • Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
  • Django (1.10, 1.11, 2.0 alpha)

The following packages are optional:

以下軟件包是可選的:

 

Installation

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.

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框架將為您設置。

 

Quickstart

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

 

Serializers

首先我們要定義一些序列化程序。在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設計。

 

Views

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使視圖邏輯組織得很好,並且非常簡潔。

 

URLs

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,那么這是非常有用的。

 

Settings

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組件

接下來了解下rest framework 的所有組件,並且得知它們是如何組合在一起的,這是非常值得去學習的。

  • 1 - Serialization 序列化
  • 2 - Requests & Responses 請求 & 響應
  • 3 - Class-based views 基於類的視圖
  • 4 - Authentication & permissions 身份驗證 & 權限
  • 5 - Relationships & hyperlinked APIs 這個貌似還沒用過,暫時留着吧,哈哈~
  • 6 - Viewsets & routers 視圖和路由
  • 7 - Schemas & client libraries 模式和客戶端庫(虛位以待~)

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM