【Django學習】Django Rest Framework 的使用


Django REST framework 是用於構建Web API 的強大而靈活的工具包。本質上DRF是django的一個app(startproject)

   DRF中文文檔:http://www.sinodocs.cn/

   安裝:安裝在想用的Python解釋器下,例如:在終端cd到/python/lib/site-packages,然后執行 pip install djangorestframework

DRF的一些組件:

     1 APIView (所有的功能都是基於APIView的)*****
     2 解析器組件 *****
     3 序列化組件 *****

     4 視圖組件

     5 認證組件 *****
     6 權限組件 *****
     7 頻率組件
     8 url注冊器組件
     9 響應器組件
     10 分頁器組件

     11 filter:過濾、查找、排序

1.APIView

  APIView的使用
  APIView執行流程
  APIView 源碼剖析

 

2.解析器組件

  解析器組件的使用
  解析器組件的源碼流程
  DRF解析器源碼剖析

 

3.序列化組件(serializers)的使用及接口設計

  接口類型 示例
  通過序列化組件進行get接口設計 流程
  通過序列化組件進行get接口設計 示例

 

  通過序列化組件進行post接口設計 流程
  通過序列化組件進行post接口設計 示例

 

  通過序列化組件進行get,update,put單條數據接口設計 流程
  通過序列化組件進行get,update,put單條數據接口設計 示例

 

  通過序列化組件進行get,post,單條數據get,put,delete 接口設計(使用視圖組件的mixin進行接口邏輯優化) 示例
  通過序列化組件進行get,post,單條數據get,put,delete 接口設計(使用視圖組件的view進行接口邏輯優化) 示例
  通過序列化組件進行get,post,單條數據get,put,delete 接口設計(使用視圖組件的viewset進行接口邏輯優化) 示例

 

4.視圖組件(mixin,genericview,viewset)

  視圖組件是用來優化接口邏輯的

(1) 使用視圖組件的mixin進行接口邏輯優化

  使用視圖組件的mixin進行接口邏輯優化 流程
  使用視圖組件的mixin進行接口邏輯優化 示例

 

(2) 使用視圖組件的view進行接口邏輯優化

  使用視圖組件的view進行接口邏輯優化 流程
  使用視圖組件的view進行接口邏輯優化 示例

 

(3) 使用視圖組件的viewset進行接口邏輯優化

  使用視圖組件的viewset進行接口邏輯優化 流程
  使用視圖組件的viewset進行接口邏輯優化 示例

 

  使用ModelViewSet也可以自定義一些返回值 示例

 

5.認證組件(token) 

  認證組件使用方式及源碼剖析
  給指定的數據接口做認證 示例
  全局認證 示例
  注意:多個認證類時,只需在最后一個認證類中返回值即可

 

6.權限組件

  權限組件 使用流程
  權限組件 示例

 

7.頻率組件

  局部 使用DRF的簡單頻率控制來控制用戶訪問頻率
  局部 使用DRF的簡單頻率控制來控制用戶訪問頻率 示例

 

  全局 使用DRF的簡單頻率控制來控制用戶訪問頻率
  全局 使用DRF的簡單頻率控制來控制用戶訪問頻率 示例

 

 8.url注冊器組件

  url注冊器組件的使用
  url注冊器組件的使用 示例

 

9.響應器組件

  響應器組件的使用

 

10.分頁器組件

  局部 使用分頁器組件
  局部 使用分頁器組件 示例

 

  全局 使用分頁器組件
  全局 使用分頁器組件 示例

 

11.filter

字段過濾

  filter過濾 示例

一般過濾可以重寫get_queryset方法實現,這時候就可以去掉queryset這個屬性了:

  View Code

現在就可以通過在url里指定參數price_min來實現對獲取到的商品價格的過濾了。

注意在使用這種方法時,要在router.register里配置base_name,不然運行不了。

 

還可以使用django-filter,這個要把它注冊為app,然后就能用了(因為這時候不需要重寫get_queryset方法了,所以就需要把queryset這個屬性拿回來)。然后可以自定義一個filters.py用來寫自定義過濾規則的過濾器:

  View Code

然后在views.py的相關視圖類里指定filter_class為這個自定義的過濾器類:

  View Code

在這個例子里配置完了之后,效果就是可以在url里指定min_price和max_price的值,來控制所返回的JSON中上shop_price值所在的區間,實現區間過濾;使用name實現模糊查詢。

查找

要實現查找,只要在視圖層配置filters.SearchFilter和search_fields=要查找的字段元組即可:

  View Code

一些符號可以實現復雜的查找方式,比如以。。開頭,全文搜索之類的。

排序

要實現排序,只要在視圖層配置filters.OrderingFilter和ordering_fields=要排序的字段即可:

  View Code

 

使用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__"
 
 轉載:https://www.cnblogs.com/lbzbky/articles/11829007.html


免責聲明!

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



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