Django Rest Framework

一 什麼是RESTful 

  • REST與技術無關,表明的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯爲「表徵狀態轉移」
  • REST從資源的角度類審視整個網絡,它將分佈在網絡中某個節點的資源經過URL進行標識,客戶端應用經過URL來獲取資源的表徵,得到這些表徵導致這些應用轉變狀態
  • REST與技術無關,表明的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯爲「表徵狀態轉移」
  • 全部的數據,不過是經過網絡獲取的仍是操做(增刪改查)的數據,都是資源,將一切數據視爲資源是REST區別與其餘架構風格的最本質屬性
  • 對於REST這種面向資源的架構風格,有人提出一種全新的結構理念,即:面向資源架構(ROA:Resource Oriented Architecture)

二  RESTful  API設計

  • API與用戶的通訊協議,老是使用HTTPs協議
  • 域名 
    • https://api.example.com                         儘可能將API部署在專用域名(會存在跨域問題)
    • https://example.org/api/                        API很簡單
  • 版本
    • URL,如:https://api.example.com/v1/
    • 請求頭                                                  跨域時,引起發送屢次請求
  • 路徑,視網絡上任何東西都是資源,均使用名詞表示(可複數)
    • https://api.example.com/v1/zoos
    • https://api.example.com/v1/animals
    • https://api.example.com/v1/employees
  • method
    • GET      :從服務器取出資源(一項或多項)
    • POST    :在服務器新建一個資源
    • PUT      :在服務器更新資源(客戶端提供改變後的完整資源)
    • PATCH  :在服務器更新資源(客戶端提供改變的屬性)
    • DELETE :從服務器刪除資源
  • 過濾,經過在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:指定篩選條件
  • 狀態碼 
OK - [GET]:服務器成功返回用戶請求的數據,該操做是冪等的(Idempotent)。
CREATED - [POST/PUT/PATCH]:用戶新建或修改數據成功。
Accepted - [*]:表示一個請求已經進入後臺排隊(異步任務)
NO CONTENT - [DELETE]:用戶刪除數據成功。
INVALID REQUEST - [POST/PUT/PATCH]:用戶發出的請求有錯誤,服務器沒有進行新建或修改數據的操做,該操做是冪等的。
Unauthorized - [*]:表示用戶沒有權限(令牌、用戶名、密碼錯誤)。
Forbidden - [*] 表示用戶獲得受權(與401錯誤相對),可是訪問是被禁止的。
NOT FOUND - [*]:用戶發出的請求針對的是不存在的記錄,服務器沒有進行操做,該操做是冪等的。
Not Acceptable - [GET]:用戶請求的格式不可得(好比用戶請求JSON格式,可是隻有XML格式)。
Gone -[GET]:用戶請求的資源被永久刪除,且不會再獲得的。
Unprocesable entity - [POST/PUT/PATCH] 當建立一個對象時,發生一個驗證錯誤。
INTERNAL SERVER ERROR - [*]:服務器發生錯誤,用戶將沒法判斷髮出的請求是否成功。

更多看這裏:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

經常使用狀態碼列表
View Code
  • 錯誤處理,狀態碼是4xx時,應返回錯誤信息,error當作key。
    1
    2
    3
    {
         error:  "Invalid API key"
    }
  • 返回結果,針對不一樣操做,服務器向用戶返回的結果應該符合如下規範。
    1
    2
    3
    4
    5
    6
    GET  / collection:返回資源對象的列表(數組)
    GET  / collection / resource:返回單個資源對象
    POST  / collection:返回新生成的資源對象
    PUT  / collection / resource:返回完整的資源對象
    PATCH  / collection / resource:返回完整的資源對象
    DELETE  / collection / resource:返回一個空文檔
  • Hypermedia API,RESTful API最好作到Hypermedia,即返回結果中提供連接,連向其餘API方法,使得用戶不查文檔,也知道下一步應該作什麼。
    1
    2
    3
    4
    5
    6
    { "link" : {
       "rel" :    "collection https://www.example.com/zoos" ,
       "href" :   "https://api.example.com/zoos" ,
       "title" "List of zoos" ,
       "type" :   "application/vnd.yourformat+json"
    }}

  摘自:http://www.ruanyifeng.com/blog/2014/05/restful_api.html html

三 基於Django的實現

路由系統:python

urlpatterns = [
    url(r'^users', Users.as_view()),
]

CBV視圖:web

from django.views import View
from django.http import JsonResponse
 
class Users(View):
    def get(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)
 
    def post(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200) 

 

四. 基於Django Rest Framework框架實現

1. 基本流程

url.pydjango

1
2
3
4
5
6
from  django.conf.urls  import  url, include
from  web.views.s1_api  import  TestView
 
urlpatterns  =  [
     url(r '^test/' , TestView.as_view()),
]

views.pyjson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from  rest_framework.views  import  APIView
from  rest_framework.response  import  Response
 
 
class  TestView(APIView):
     def  dispatch( self , request,  * args,  * * kwargs):
         """
         請求到來以後,都要執行dispatch方法,dispatch方法根據請求方式不一樣觸發 get/post/put等方法
         
         注意:APIView中的dispatch方法有好多好多的功能
         """
         return  super ().dispatch(request,  * args,  * * kwargs)
 
     def  get( self , request,  * args,  * * kwargs):
         return  Response( 'GET請求,響應內容' )
 
     def  post( self , request,  * args,  * * kwargs):
         return  Response( 'POST請求,響應內容' )
 
     def  put( self , request,  * args,  * * kwargs):
         return  Response( 'PUT請求,響應內容' )

上述是rest framework框架基本流程,重要的功能是在APIView的dispatch中觸發。api

2.  認證和受權

a. 用戶url傳入的token認證

from django.conf.urls import url, include
from web.viewsimport TestView

urlpatterns = [
    url(r'^test/', TestView.as_view()),
]

urls.py
View Code
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from rest_framework import exceptions

token_list = [
    'sfsfss123kuf3j123',
    'asijnfowerkkf9812',
]


class TestAuthentication(BaseAuthentication):
    def authenticate(self, request):
        """
        用戶認證,若是驗證成功後返回元組: (用戶,用戶Token)
        :param request: 
        :return: 
            None,表示跳過該驗證;
                若是跳過了全部認證,默認用戶和Token和使用配置文件進行設置
                self._authenticator = None
                if api_settings.UNAUTHENTICATED_USER:
                    self.user = api_settings.UNAUTHENTICATED_USER()
                else:
                    self.user = None
        
                if api_settings.UNAUTHENTICATED_TOKEN:
                    self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                else:
                    self.auth = None
            (user,token)表示驗證經過並設置用戶名和Token;
            AuthenticationFailed異常
        """
        val = request.query_params.get('token')
        if val not in token_list:
            raise exceptions.AuthenticationFailed("用戶認證失敗")

        return ('登陸用戶', '用戶token')

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        # 驗證失敗時,返回的響應頭WWW-Authenticate對應的值
        pass


class TestView(APIView):
    authentication_classes = [TestAuthentication, ]
    permission_classes = []

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)
        return Response('GET請求,響應內容')

    def post(self, request, *args, **kwargs):
        return Response('POST請求,響應內容')

    def put(self, request, *args, **kwargs):
        return Response('PUT請求,響應內容')
View Code

b. 請求頭認證

  urls.py
複製代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from rest_framework import exceptions

token_list = [
    'sfsfss123kuf3j123',
    'asijnfowerkkf9812',
]


class TestAuthentication(BaseAuthentication):
    def authenticate(self, request):
        """
        用戶認證,若是驗證成功後返回元組: (用戶,用戶Token)
        :param request: 
        :return: 
            None,表示跳過該驗證;
                若是跳過了全部認證,默認用戶和Token和使用配置文件進行設置
                self._authenticator = None
                if api_settings.UNAUTHENTICATED_USER:
                    self.user = api_settings.UNAUTHENTICATED_USER()
                else:
                    self.user = None
        
                if api_settings.UNAUTHENTICATED_TOKEN:
                    self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                else:
                    self.auth = None
            (user,token)表示驗證經過並設置用戶名和Token;
            AuthenticationFailed異常
        """
        import base64
        auth = request.META.get('HTTP_AUTHORIZATION', b'')
        if auth:
            auth = auth.encode('utf-8')
        auth = auth.split()
        if not auth or auth[0].lower() != b'basic':
            raise exceptions.AuthenticationFailed('驗證失敗')
        if len(auth) != 2:
            raise exceptions.AuthenticationFailed('驗證失敗')
        username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':')
        if username == 'alex' and password == '123':
            return ('登陸用戶', '用戶token')
        else:
            raise exceptions.AuthenticationFailed('用戶名或密碼錯誤')

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        return 'Basic realm=api'


class TestView(APIView):
    authentication_classes = [TestAuthentication, ]
    permission_classes = []

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)
        return Response('GET請求,響應內容')

    def post(self, request, *args, **kwargs):
        return Response('POST請求,響應內容')

    def put(self, request, *args, **kwargs):
        return Response('PUT請求,響應內容')
複製代碼

c. 多個認證規則跨域

  urls.py
  views.py

d. 認證和權限數組

  urls.py
  views.py

e. 全局使用服務器

上述操做中均是對單獨視圖進行特殊配置,若是想要對全局進行配置,則須要再配置文件中寫入便可。restful

  settings.py
  urls.py
  views.py

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 錯誤處理,狀態碼是4xx時,應返回錯誤信息,error當作key。
    1
    2
    3
    {
         error:  "Invalid API key"
    }
  • 返回結果,針對不一樣操做,服務器向用戶返回的結果應該符合如下規範。
    1
    2
    3
    4
    5
    6
    GET  / collection:返回資源對象的列表(數組)
    GET  / collection / resource:返回單個資源對象
    POST  / collection:返回新生成的資源對象
    PUT  / collection / resource:返回完整的資源對象
    PATCH  / collection / resource:返回完整的資源對象
    DELETE  / collection / resource:返回一個空文檔
相關文章
相關標籤/搜索