1. 程式人生 > 實用技巧 >Django-DRF框架

Django-DRF框架

一、RESTfull設計風格

1、什麼是RESTfull?

  1)REST:即Representational State Transfer的縮寫。維基百科稱其為“具象狀態傳輸”,國內大部分人理解為“表現層狀態轉化”。

  2)具象的:就是指表現層,要表現的物件也就是“資源”,什麼是資源呢?網站就是資源共享的東西,客戶端(瀏覽器)訪問web伺服器,所獲取的就叫資源。比如html,txt,json,圖片,視訊等等。

  3)表現:比如,文字可以用txt格式表現,也可以用HTML格式、XML格式、JSON格式表現,甚至可以採用二進位制格式;圖片可以用JPG格式表現,也可以用PNG格式表現。

      瀏覽器通過URL確定一個資源,但是如何確定它的具體表現形式呢?應該在HTTP請求的頭資訊中用Accept和Content-Type欄位指定,這兩個欄位才是對"表現層"的描述。

  4)狀態轉換:就是客戶端和伺服器互動的一個過程,在這個過程中, 勢必涉及到資料和狀態的變化, 這種變化叫做狀態轉換。

         網際網路通訊協議HTTP協議,客戶端訪問必然使用HTTP協議,如果客戶端想要操作伺服器,必須通過某種手段,讓伺服器端發生"狀態轉化"(State Transfer)。

  總結:

    REST與技術無關,代表的是一種軟體架構風格

    REST從資源的角度審視審視整個網路,它將分佈在網路中某個節點的資源通過URL進行標識

    所有的資料,無論是通過網路獲取的還是操作(增刪改查)的資料,都是資源。將一切資料視為資源是REST區別於其他架構風格的最本質的屬性。

    每一個URL代表一種資源

    客戶端和伺服器之間,傳遞這種資源的某種表現層;

    客戶端通過HTTP動詞對伺服器端資源進行操作,實現“表現層狀態轉化”(GET,POST,PUT,DELETE)

2、RESTfull設計規範

  1.域名

    1)子域名方式

      https://api.example.com 儘量將API部署在專用域名(會存在跨域問題)

      https://www.example.com

    2)url方式

      https://example.org

      https://example.org/api/ API很簡單

  2.版本

    將API的版本號放入URL中。

    https://api.example.com/v1/

    https://api.example.com/v2/

    https://api.example.com/v3/

  3.路徑

    路徑又稱“終點”,表示API的具體網址,每個網址代表一種資源

    1) 資源作為網址,只能有名詞,不能有動詞,而且所用的名詞往往與資料庫的表名對應。

    2)API中的名詞應該使用複數。無論子資源或者所有資源。

      /getProducts    不符合REST風格

      /Orders       符合REST風格

      獲取單個產品:http://127.0.0.1:8080/AppName/products/1

      獲取所有產品:http://127.0.0.1:8080/AppName/products

   4.方式

      GET :從伺服器取出資源(一項或多項)

      POST :在伺服器新建一個資源

      PUT :在伺服器更新資源(客戶端提供改變的完整資源)

      PATCH :在伺服器更新資源(客戶端提供改變的屬性)

      DELETE :從伺服器刪除資源

   5.過濾

    通過在url上傳參的形式傳遞搜尋條件

      https://api.example.com/v1/zoos?limit=10:指定返回記錄的數量

      https://api.example.com/v1/zoos?offset=10:指定返回記錄的開始位置

      https://api.example.com/v1/zoos?page=2&per_page=100:指定第幾頁,以及每頁的記錄數

      https://api.example.com/v1/zoos?sortby=name&order=asc:指定返回結果按照哪個屬性排序,以及排序順序

      https://api.example.com/v1/zoos?animal_type_id=1:指定篩選條件

   6.狀態碼

'''1. 2XX請求成功'''
# 200 請求成功,一般用於GET與POST請求
# 201 Created - [POST/PUT/PATCH]:使用者新建或修改資料成功。
# 202 Accepted - [*]:表示一個請求已經進入後臺排隊(非同步任務)
# 204 NO CONTENT - [DELETE]:使用者刪除資料成功。
'''2. 3XX重定向'''
# 301 NO CONTENT - 永久重定向
# 302 NO CONTENT - 臨時重定向
'''3. 4XX客戶端錯誤'''
# 400 INVALID REQUEST - [POST/PUT/PATCH]:使用者發出的請求有錯誤。
# 401 Unauthorized - [*]:表示使用者沒有許可權(令牌、使用者名稱、密碼錯誤)。
# 403 Forbidden - [*] 表示使用者得到授權(與401錯誤相對),但是訪問是被禁止的。
# 404 NOT FOUND - [*]:使用者發出的請求針對的是不存在的記錄。
# 406 Not Acceptable - [GET]:使用者請求的格式不可得(比如使用者請求JSON格式,但是隻有XML格式)。
# 410 Gone -[GET]:使用者請求的資源被永久刪除,且不會再得到的。
# 422 Unprocesable entity - [POST/PUT/PATCH] 當建立一個物件時,發生一個驗證錯誤。
'''4. 5XX服務端錯誤'''
# 500 INTERNAL SERVER ERROR - [*]:伺服器內部錯誤,無法完成請求
# 501 Not Implemented     伺服器不支援請求的功能,無法完成請求

更多狀態碼參考:https://www.runoob.com/http/http-status-codes.html

狀態碼
狀態碼

   7.異常處理

      如果狀態碼是4xx,伺服器就應該向使用者返回出錯資訊。一般來說,返回的資訊中將error作為鍵名,出錯資訊作為鍵值即可。

      {error:"Invalid API key"}

   8.返回結果

      針對不同操作,伺服器向用戶返回的結果應該符合以下規範。

        GET /collection:返回資源物件的列表(陣列)

        GET /collection/resource:返回單個資源物件

        POST /collection:返回新生成的資源物件

        PUT /collection/resource:返回完整的資源物件

        PATCH /collection/resource:返回完整的資源物件

        DELETE /collection/resource:返回一個空文件

   9.超媒體(Hypermedia API)

      RESTful API最好做到Hypermedia(即返回結果中提供連結,連向其他API方法),使得使用者不查文件,也知道下一步應該做什麼。

      比如,Github的API就是這種設計,訪問api.github.com會得到一個所有可用API的網址列表。

{
  "current_user_url": "https://api.github.com/user",
  "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}",
  "authorizations_url": "https://api.github.com/authorizations",
  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
  "commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}",
  "emails_url": "https://api.github.com/user/emails",
  "emojis_url": "https://api.github.com/emojis",
  "events_url": "https://api.github.com/events",
  "feeds_url": "https://api.github.com/feeds",
  "followers_url": "https://api.github.com/user/followers",
  "following_url": "https://api.github.com/user/following{/target}",
  "gists_url": "https://api.github.com/gists{/gist_id}",
  "hub_url": "https://api.github.com/hub",
  "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",
  "issues_url": "https://api.github.com/issues",
  "keys_url": "https://api.github.com/user/keys",
  "notifications_url": "https://api.github.com/notifications",
  "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",
  "organization_url": "https://api.github.com/orgs/{org}",
  "public_gists_url": "https://api.github.com/gists/public",
  "rate_limit_url": "https://api.github.com/rate_limit",
  "repository_url": "https://api.github.com/repos/{owner}/{repo}",
  "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",
  "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",
  "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",
  "starred_gists_url": "https://api.github.com/gists/starred",
  "team_url": "https://api.github.com/teams",
  "user_url": "https://api.github.com/users/{user}",
  "user_organizations_url": "https://api.github.com/user/orgs",
  "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",
  "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"
}

      從上面可以看到,如果想獲取當前使用者的資訊,應該去訪問api.github.com/user,然後就得到了下面結果。

{
  "message": "Requires authentication",
  "documentation_url": "https://developer.github.com/v3/users/#get-the-authenticated-user"
}

二、DRF框架的使用(Django REST Framework)

  1、所需依賴

    Python(2.7,3.2,3.3,3.5,3.6)

    Django(1.10,1.11,2.0)

  2、安裝DRF

    pip install djangorestframework

  3、配置DRF

INSTALLED_APPS = [
    ...
    'rest_framework',
]
setting.py

  4、序列化器的定義

    a.可用欄位

    b. 選項引數

    

      c. 通用引數

    d. 定義一個序列化器

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name='名稱')
    bpub_date = models.DateField(verbose_name='釋出日期', null=True)
    bread = models.IntegerField(default=0, verbose_name='閱讀量')
    bcomment = models.IntegerField(default=0, verbose_name='評論量')
    image = models.ImageField(upload_to='booktest', verbose_name='圖片', null=True)
model.py
class BookInfoSerializer(serializers.Serializer):
    """圖書資料序列化器"""
    id = serializers.IntegerField(label='ID', read_only=True)
    btitle = serializers.CharField(label='名稱', max_length=20)
    bpub_date = serializers.DateField(label='釋出日期', required=False)
    bread = serializers.IntegerField(label='閱讀量', required=False)
    bcomment = serializers.IntegerField(label='評論量', required=False)
    image = serializers.ImageField(label='圖片', required=False)
serializers.py

    e.Serializer的構造方法為:

      serializer = BookIndoSerializers(instance=None,data = data, **kwargs)    

      說明:

        1)用於序列化時,將模型類物件傳入instance引數

        2)用於反序列化時,將要被反序列化的資料傳入data引數

  5、單表序列化器的序列化使用:

from booktest.serializers import BookInfoSerializer
from booktest.models import BookInfo

#單個數據序列化
book = BookInfo.objects.get(id=2)
serializer = BookInfoSerializer(book)
#獲取序列化結果
data=serializer.data

#多資料的序列化
book_qs = BookInfo.objects.all()
serializer = BookInfoSerializer(book_qs, many=True)
data = serializer.data
Views.py

  6、單表序列化器的反序列化使用:

class BookInfoSerializer(serializers.Serializer):
    """圖書資料序列化器"""
    ...

    def create(self, validated_data):
        """新建"""
        return BookInfo(**validated_data)

    def update(self, instance, validated_data):
        """更新,instance為要更新的物件例項"""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        return instance
zerializers.py
from db.serializers import BookInfoSerializer
data = {'btitle': '封神演義'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # True
serializer.save()  # <BookInfo: 封神演義>


views.py
views.py

    注意:

      預設序列化器必須傳遞所有required的欄位,否則會丟擲驗證異常。但是我們可以使用partial引數來允許部分欄位更新

      serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)

  7、一對多序列化器的使用:

class HeroInfoSerializer(serializers.Serializer):
    """英雄資料序列化器"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='名字', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性別', required=False)
    hcomment = serializers.CharField(label='描述資訊', max_length=200, required=False, allow_null=True)
    
    
#1) PrimaryKeyRelatedField
#此欄位將被序列化為關聯物件的主鍵。
    hbook = serializers.PrimaryKeyRelatedField(label='圖書', read_only=True)

from booktest.serializers import HeroInfoSerializer
from booktest.models import HeroInfo
hero = HeroInfo.objects.get(id=6)
serializer = HeroInfoSerializer(hero)
serializer.data
# {'id': 6, 'hname': '喬峰', 'hgender': 1, 'hcomment': '降龍十八掌', 'hbook': 2}

#2) StringRelatedField
#此欄位將被序列化為關聯物件的字串表示方式(即__str__方法的返回值)
hbook = serializers.StringRelatedField(label='圖書')
#結果
#{'id': 6, 'hname': '喬峰', 'hgender': 1, 'hcomment': '降龍十八掌', 'hbook': '天龍八部'}

3)使用關聯物件的序列化器
#hbook = BookInfoSerializer()
#結果
#{'id': 6, 'hname': '喬峰', 'hgender': 1, 'hcomment': '降龍十八掌', 'hbook': OrderedDict([('id', 2), ('btitle', '天龍八部')te', '1986-07-24'), ('bread', 36), ('bcomment', 40), ('image', None)])}

#4)SlugRelatedField
#此欄位將被序列化為關聯物件的指定欄位資料
#hbook = serializers.SlugRelatedField(label='圖書', read_only=True, slug_field='bpub_date')
#結果
#{'id': 6, 'hname': '喬峰', 'hgender': 1, 'hcomment': '降龍十八掌', 'hbook': datetime.date(1986, 7, 24)}
serializers.py