一. 什麼是RESTful html
一、REST與技術無關,表明的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯爲「表徵狀態轉移」python
二、REST從資源的角度類審視整個網絡,它將分佈在網絡中某個節點的資源經過URL進行標識,客戶端應用經過URL來獲取資源的表徵,得到這些表徵導致這些應用轉變狀態web
三、全部的數據,不過是經過網絡獲取的仍是操做(增刪改查)的數據,都是資源,將一切數據視爲資源是REST區別與其餘架構風格的最本質屬性數據庫
四、對於REST這種面向資源的架構風格,有人提出一種全新的結構理念,即:面向資源架構(ROA:Resource Oriented Architecture)django
二. RESTful API設計json
一、API與用戶的通訊協議,老是使用HTTPs協議。api
二、域名跨域
https://api.example.com 儘可能將API部署在專用域名(會存在跨域問題)數組
https://example.org/api/ API很簡單瀏覽器
三、版本
URL,如:https://api.example.com/v1/ 請求頭跨域時,引起發送屢次請求
四、路徑,視網絡上任何東西都是資源,均使用名詞表示(可複數即後面加s)
https://api.example.com/v1/zoos
https://api.example.com/v1/animals
https://api.example.com/v1/employees
五、method
GET :從服務器取出資源(一項或多項)
POST :在服務器新建一個資源
PUT :在服務器更新資源(客戶端提供改變後的完整資源,所有更新用put)
PATCH :在服務器更新資源(客戶端提供改變的屬性,局部更新用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:指定篩選條件
七、狀態碼
200 OK - [GET]:服務器成功返回用戶請求的數據,該操做是冪等的(Idempotent)。 201 CREATED - [POST/PUT/PATCH]:用戶新建或修改數據成功。 202 Accepted - [*]:表示一個請求已經進入後臺排隊(異步任務) 204 NO CONTENT - [DELETE]:用戶刪除數據成功。 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] 當建立一個對象時,發生一個驗證錯誤。 500 INTERNAL SERVER ERROR - [*]:服務器發生錯誤,用戶將沒法判斷髮出的請求是否成功。
八、錯誤處理,狀態碼是4xx時,應返回錯誤信息,error當作key。
{error: "Invalid API key"}
九、返回結果,針對不一樣操做,服務器向用戶返回的結果應該符合如下規範。
GET /collection:返回資源對象的列表(數組) GET /collection/resource:返回單個資源對象 POST /collection:返回新生成的資源對象 PUT /collection/resource:返回完整的資源對象 PATCH /collection/resource:返回完整的資源對象 DELETE /collection/resource:返回一個空文檔
十、Hypermedia API,RESTful API最好作到Hypermedia,即返回結果中提供連接,連向其餘API方法,使得用戶不查文檔,也知道下一步應該作什麼。
{"link": { "rel": "collection https://www.example.com/zoos", "href": "https://api.example.com/zoos", "title": "List of zoos", "type": "application/vnd.yourformat+json" }}
三. 基於Django實現
一、路由系統:
urlpatterns = [ url(r'^users', Users.as_view()), ]
二、CBV視圖:
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.py
from django.conf.urls import url, include from web.views.s1_api import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
二、views.py
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中觸發
二、版本
a. 基於url的get傳參方式。如:/users?version=v1
全局配置:在settings中配置 REST_FRAMEWORK = { 'DEFAULT_VERSION': 'v1', # 默認版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 容許的版本
'VERSION_PARAM': 'version' # URL中獲取值的key
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.QueryParameterVersioning", #指定默認版本傳參路徑
} 局部配置:在view中配置 局部配置就須要在每一個view視圖中添加上versioning_class=QueryParameterVersionin
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view(),name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import QueryParameterVersioning class TestView(APIView): //versioning_class = QueryParameterVersioning def get(self, request, *args, **kwargs): # 獲取版本
print(request.version) # 獲取版本管理的類
print(request.versioning_scheme) # 反向生成URL
reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
b. 基於url的正則方式如:/v1/users/
REST_FRAMEWORK = { 'DEFAULT_VERSION': 'v1', # 默認版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 容許的版本
'VERSION_PARAM': 'version' # URL中獲取值的key
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning", }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^(?P<version>[v1|v2]+)/test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import URLPathVersioning class TestView(APIView): versioning_class = URLPathVersioning def get(self, request, *args, **kwargs): # 獲取版本
print(request.version) # 獲取版本管理的類
print(request.versioning_scheme) # 反向生成URL
reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
c. 基於 accept 請求頭方式如:Accept: application/json; version=1.0
REST_FRAMEWORK = { 'DEFAULT_VERSION': 'v1', # 默認版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 容許的版本
'VERSION_PARAM': 'version' # URL中獲取值的key
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.AcceptHeaderVersioning", }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import AcceptHeaderVersioning class TestView(APIView): versioning_class = AcceptHeaderVersioning def get(self, request, *args, **kwargs): # 獲取版本 HTTP_ACCEPT頭
print(request.version) # 獲取版本管理的類
print(request.versioning_scheme) # 反向生成URL
reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
d. 基於主機名方法如:v1.example.com
ALLOWED_HOSTS = ['*'] REST_FRAMEWORK = { 'DEFAULT_VERSION': 'v1', # 默認版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 容許的版本
'VERSION_PARAM': 'version' # URL中獲取值的key
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.HostNameVersioning", }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import HostNameVersioning class TestView(APIView): versioning_class = HostNameVersioning def get(self, request, *args, **kwargs): # 獲取版本
print(request.version) # 獲取版本管理的類
print(request.versioning_scheme) # 反向生成URL
reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
e. 基於django路由系統的namespace如:example.com/v1/users/
REST_FRAMEWORK = { 'DEFAULT_VERSION': 'v1', # 默認版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 容許的版本
'VERSION_PARAM': 'version' # URL中獲取值的key
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^v1/', ([ url(r'test/', TestView.as_view(), name='test'), ], None, 'v1')), url(r'^v2/', ([ url(r'test/', TestView.as_view(), name='test'), ], None, 'v2')), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.versioning import NamespaceVersioning class TestView(APIView): versioning_class = NamespaceVersioning def get(self, request, *args, **kwargs): # 獲取版本
print(request.version) # 獲取版本管理的類
print(request.versioning_scheme) # 反向生成URL
reverse_url = request.versioning_scheme.reverse('test', request=request) print(reverse_url) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
f.總結:
一、若是想要看到'rest_framework'特製的錯誤頁面就須要把'rest_framework'給註冊到settings中的INSTALLED_APPS中 2、rest_framework生命週期: 1. 中間件 2. 路由系統 3. 視圖 - request二次封裝(解析器,認證,選擇,view+參數) - try: - 獲取版本 - 認證 - 權限 - 節流 - response = GET/POST/DELETE等方法 - except: - response = 異常 - 處理響應內容 3、版本控制: 視圖類中配置: from rest_framework.versioning import URLPathVersioning class UsersView(APIView): versioning_class = URLPathVersioning 配置文件中: 註冊APP: 'rest_framework', REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning", "VERSION_PARAM":"version", "DEFAULT_VERSION":'v1', "ALLOWED_VERSIONS":['v1','v2'] } 獲取和反向生成URL print(request.version) print(request.versioning_scheme.reverse(viewname='xxxx',request=request))
三、認證
a. 用戶url傳入的token認證
from django.conf.urls import url, include from web.viewsimport TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
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)://本身寫一個認證的類,而且必須繼承BaseAuthentication類,並且要繼承和從新BaseAuthentication這個類下的方法 def authenticate(self, request): """ 用戶認證,若是驗證成功後返回元組: (用戶,用戶Token) 若是返回None,表示跳過該驗證; 若是跳過了全部認證,默認用戶和Token和使用配置文件進行設置 """ val = request.query_params.get('token') //query_params封裝了原生的request的GET請求,等同於_request.GET if val not in token_list: raise exceptions.AuthenticationFailed("用戶認證失敗") return ('登陸用戶', '用戶token') def authenticate_header(self, request): # 驗證失敗時,返回的響應頭WWW-Authenticate對應的值,通常不用
pass
class TestView(APIView): authentication_classes = [TestAuthentication, ]//局部應用 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請求,響應內容') 註釋:用戶必須先認證經過TestAuthentication類,即能成功登錄才能訪問TestView類下的方法
b、請求頭認證
from django.conf.urls import url, include from web.viewsimport TestView urlpatterns = [ url(r'^test/', TestView.as_view()),
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)None,表示跳過該驗證;若是跳過了全部認證,默認用戶和Token和使用配置文件進行設置
import base64 auth = request.META.get('HTTP_AUTHORIZATION', b'') #META封裝了_request.POST
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 'Basic realm=api'
class TestView(APIView): authentication_classes = [TestAuthentication, ] 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、多個認證規則
from django.conf.urls import url, include from web.views.s2_auth import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
#!/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 Test1Authentication(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()# 默認值爲:None else: self.auth = None (user,token)表示驗證經過並設置用戶名和Token; AuthenticationFailed異常 """
import base64 auth = request.META.get('HTTP_AUTHORIZATION', b'') if auth: auth = auth.encode('utf-8') else: return None print(auth,'xxxx') 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'
pass
class Test2Authentication(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()# 默認值爲:None 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. """
pass
class TestView(APIView): authentication_classes = [Test1Authentication, Test2Authentication] 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請求,響應內容') 複製代碼
四、權限
a、
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.permissions import BasePermission from rest_framework.request import Request from rest_framework import exceptions token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812', ] class TestAuthentication(BaseAuthentication): def authenticate(self, request): val = request.query_params.get('token') if val not in token_list: raise exceptions.AuthenticationFailed("用戶認證失敗") return ('登陸用戶', '用戶token') def authenticate_header(self, request): pass
class TestPermission(BasePermission): message = "權限驗證失敗"
def has_permission(self, request, view): """ 判斷是否有權限訪問當前請求,return: True有權限;False無權限 """
if request.user == "管理員": return True # GenericAPIView中get_object時調用
def has_object_permission(self, request, view, obj): """ 視圖繼承GenericAPIView,並在其中使用get_object時獲取對象時,觸發單獨對象權限驗證,return: True有權限;False無權限 """
if request.user == "管理員": return True class TestView(APIView): # 認證的動做是由request.user觸發
authentication_classes = [TestAuthentication, ] # 權限
# 循環執行全部的權限
permission_classes = [TestPermission, ] def get(self, request, *args, **kwargs): # self.dispatch
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請求,響應內容')
b、全局設置
REST_FRAMEWORK = { 'UNAUTHENTICATED_USER': None, 'UNAUTHENTICATED_TOKEN': None, "DEFAULT_AUTHENTICATION_CLASSES": [ "web.utils.TestAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "web.utils.TestPermission", ], }
五、限制用戶訪問次數
a、基於用戶IP限制訪問頻率
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
import time from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import exceptions from rest_framework.throttling import BaseThrottle from rest_framework.settings import api_settings # 保存訪問記錄
RECORD = { '用戶IP': [12312139, 12312135, 12312133, ] } class TestThrottle(BaseThrottle): ctime = time.time def get_ident(self, request): """ 根據用戶IP和代理IP,當作請求者的惟一IP Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR if present and number of proxies is > 0. If not use all of HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. """ xff = request.META.get('HTTP_X_FORWARDED_FOR') remote_addr = request.META.get('REMOTE_ADDR') num_proxies = api_settings.NUM_PROXIES if num_proxies is not None: if num_proxies == 0 or xff is None: return remote_addr addrs = xff.split(',') client_addr = addrs[-min(num_proxies, len(addrs))] return client_addr.strip() return ''.join(xff.split()) if xff else remote_addr def allow_request(self, request, view): """ 是否仍然在容許範圍內 Return `True` if the request should be allowed, `False` otherwise. :param request: :param view: :return: True,表示能夠經過;False表示已超過限制,不容許訪問 """
# 獲取用戶惟一標識(如:IP)
# 容許一分鐘訪問10次
num_request = 10 time_request = 60 now = self.ctime() ident = self.get_ident(request) self.ident = ident if ident not in RECORD: RECORD[ident] = [now, ] return True history = RECORD[ident] while history and history[-1] <= now - time_request: history.pop() if len(history) < num_request: history.insert(0, now) return True def wait(self): """ 多少秒後能夠容許繼續訪問 Optionally, return a recommended number of seconds to wait before the next request. """ last_time = RECORD[self.ident][0] now = self.ctime() return int(60 + last_time - now) class TestView(APIView): throttle_classes = [TestThrottle, ] def get(self, request, *args, **kwargs): # self.dispatch
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請求,響應內容') def throttled(self, request, wait): """ 訪問次數被限制時,定製錯誤信息 """
class Throttled(exceptions.Throttled): default_detail = '請求被限制.' extra_detail_singular = '請 {wait} 秒以後再重試.' extra_detail_plural = '請 {wait} 秒以後再重試.'
raise Throttled(wait)
b、基於用戶IP顯示訪問頻率(利於Django緩存)
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'test_scope': '10/m', }, }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import exceptions from rest_framework.throttling import SimpleRateThrottle class TestThrottle(SimpleRateThrottle): # 配置文件定義的顯示頻率的Key
scope = "test_scope"
def get_cache_key(self, request, view): """ Should return a unique cache-key which can be used for throttling. Must be overridden. May return `None` if the request should not be throttled. """
if not request.user: ident = self.get_ident(request) else: ident = request.user return self.cache_format % { 'scope': self.scope, 'ident': ident } class TestView(APIView): throttle_classes = [TestThrottle, ] def get(self, request, *args, **kwargs): # self.dispatch
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請求,響應內容') def throttled(self, request, wait): """ 訪問次數被限制時,定製錯誤信息 """
class Throttled(exceptions.Throttled): default_detail = '請求被限制.' extra_detail_singular = '請 {wait} 秒以後再重試.' extra_detail_plural = '請 {wait} 秒以後再重試.'
raise Throttled(wait)
c、view中限制請求頻率
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'xxxxxx': '10/m', }, }
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import exceptions from rest_framework.throttling import ScopedRateThrottle # 繼承 ScopedRateThrottle
class TestThrottle(ScopedRateThrottle): def get_cache_key(self, request, view): """ Should return a unique cache-key which can be used for throttling. Must be overridden. May return `None` if the request should not be throttled. """
if not request.user: ident = self.get_ident(request) else: ident = request.user return self.cache_format % { 'scope': self.scope, 'ident': ident } class TestView(APIView): throttle_classes = [TestThrottle, ] # 在settings中獲取 xxxxxx 對應的頻率限制值
throttle_scope = "xxxxxx"
def get(self, request, *args, **kwargs): # self.dispatch
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請求,響應內容') def throttled(self, request, wait): """ 訪問次數被限制時,定製錯誤信息 """
class Throttled(exceptions.Throttled): default_detail = '請求被限制.' extra_detail_singular = '請 {wait} 秒以後再重試.' extra_detail_plural = '請 {wait} 秒以後再重試.'
raise Throttled(wait)
d、匿名時用IP限制+登陸時用Token限制
REST_FRAMEWORK = { 'UNAUTHENTICATED_USER': None, 'UNAUTHENTICATED_TOKEN': None, 'DEFAULT_THROTTLE_RATES': { 'luffy_anon': '10/m', 'luffy_user': '20/m', }, }
from django.conf.urls import url, include from web.views.s3_throttling import TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.throttling import SimpleRateThrottle class LuffyAnonRateThrottle(SimpleRateThrottle): """ 匿名用戶,根據IP進行限制 """ scope = "luffy_anon"
def get_cache_key(self, request, view): # 用戶已登陸,則跳過 匿名頻率限制
if request.user: return None return self.cache_format % { 'scope': self.scope, 'ident': self.get_ident(request) } class LuffyUserRateThrottle(SimpleRateThrottle): """ 登陸用戶,根據用戶token限制 """ scope = "luffy_user"
def get_ident(self, request): """ 認證成功時:request.user是用戶對象;request.auth是token對象 :param request: :return: """
# return request.auth.token
return "user_token"
def get_cache_key(self, request, view): """ 獲取緩存key :param request: :param view: :return: """
# 未登陸用戶,則跳過 Token限制
if not request.user: return None return self.cache_format % { 'scope': self.scope, 'ident': self.get_ident(request) } class TestView(APIView): throttle_classes = [LuffyUserRateThrottle, LuffyAnonRateThrottle, ] def get(self, request, *args, **kwargs): # self.dispatch
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請求,響應內容')
e. 全局使用
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'api.utils.throttles.throttles.LuffyAnonRateThrottle', 'api.utils.throttles.throttles.LuffyUserRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'anon': '10/day', 'user': '10/day', 'luffy_anon': '10/m', 'luffy_user': '20/m', }, }
六、解析器(parser)
a、僅處理請求頭content-type爲application/json的請求體
from django.conf.urls import url, include from web.views.s5_parser import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import JSONParser class TestView(APIView): parser_classes = [JSONParser, ] def post(self, request, *args, **kwargs): print(request.content_type) # 獲取請求的值,並使用對應的JSONParser進行處理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data時,request.POST中才有值
print(request.POST) print(request.FILES) return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
b、僅處理請求頭content-type爲application/x-www-form-urlencoded 的請求體
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import FormParser class TestView(APIView): parser_classes = [FormParser, ] def post(self, request, *args, **kwargs): print(request.content_type) # 獲取請求的值,並使用對應的JSONParser進行處理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data時,request.POST中才有值
print(request.POST) print(request.FILES) return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
c、僅處理請求頭content-type爲multipart/form-data的請求體
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import MultiPartParser class TestView(APIView): parser_classes = [MultiPartParser, ] def post(self, request, *args, **kwargs): print(request.content_type) # 獲取請求的值,並使用對應的JSONParser進行處理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data時,request.POST中才有值
print(request.POST) print(request.FILES) return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8000/test/" method="post" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img">
<input type="submit" value="提交">
</form>
</body>
</html>
d. 僅上傳文件
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'test/(?P<filename>[^/]+)', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import FileUploadParser class TestView(APIView): parser_classes = [FileUploadParser, ] def post(self, request, filename, *args, **kwargs): print(filename) print(request.content_type) # 獲取請求的值,並使用對應的JSONParser進行處理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data時,request.POST中才有值
print(request.POST) print(request.FILES) return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8000/test/f1.numbers" method="post" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img">
<input type="submit" value="提交">
</form>
</body>
</html>
e. 同時多個Parser(當同時使用多個parser時,rest framework會根據請求頭content-type自動進行比對,並使用對應parser)
from django.conf.urls import url, include from web.views import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import JSONParser, FormParser, MultiPartParser class TestView(APIView): parser_classes = [JSONParser, FormParser, MultiPartParser, ] def post(self, request, *args, **kwargs): print(request.content_type) # 獲取請求的值,並使用對應的JSONParser進行處理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data時,request.POST中才有值
print(request.POST) print(request.FILES) return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')
f. 全局使用
REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser'
'rest_framework.parsers.FormParser'
'rest_framework.parsers.MultiPartParser' ] }
七、序列化(序列化用於對用戶請求數據進行驗證和數據進行序列化)
a. 自定義字段
from django.conf.urls import url, include from web.views.s6_serializers import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
from rest_framework.views import APIView from .. import models class PasswordValidator(object): def __init__(self, base): self.base = base def __call__(self, value): if value != self.base: #value是用戶發送過來的值
message = 'This field must be %s.' % self.base raise serializers.ValidationError(message) def set_context(self, serializer_field): # 執行驗證以前調用,serializer_fields是當前字段對象
pass
from rest_framework.response import Response from rest_framework import serializers class UserSerializer(serializers.Serializer): email=serializers.EmailFied() ut_title = serializers.CharField(source='ut.title',required=False) #跨表拿組相關信息,source='ut.title'表示拿組的title信息,ut確定是該表外鍵字段,requiredb=False表示能夠不填
user = serializers.CharField(min_length=6) #表示拿user字段相關信息,而且驗證字段最小長度爲6
pwd = serializers.CharField(error_messages={'required': '密碼不能爲空'}, validators=[PasswordValidator('666')])#required表示自定製錯誤信息,validators表示自定製驗證規則,請求發過來的數據要
#驗證就須要執行__call__方法,而後你就能夠在__call__方法內寫本身的驗證規則
class TestView(APIView): def get(self, request, *args, **kwargs): # instance:序列化,將數據庫查詢字段序列化爲字典而後發送 給用戶
data_list = models.UserInfo.objects.all() ser = UserSerializer(instance=data_list, many=True) #因爲ser是個列表,因此many=True
# 或
# obj = models.UserInfo.objects.all().first()
# ser = UserSerializer(instance=obj, many=False) #因爲ser是個對象,因此many=False
return Response(ser.data) #ser.data就把數據庫中的數據所有都轉換成有序字典,而且用rest_framework爲咱們封裝好的Response返回序列化後的結果
def post(self, request, *args, **kwargs): #data: 驗證,對請求發來的數據進行驗證
ser = UserSerializer(data=request.data) if ser.is_valid(): #驗證用戶發送過來的數據是否符合表字段的規範,若是都符合就打印正確字段信息,只要有一個不符合就只打印不符合字段信息
print(ser.validated_data) else: print(ser.errors) return Response('POST請求,響應內容')
b. 基於Model自動生成字段
from django.conf.urls import url, include from web.views.s6_serializers import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), ]
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from .. import models class PasswordValidator(object): def __init__(self, base): self.base = str(base) def __call__(self, value): if value != self.base: message = 'This field must be %s.' % self.base raise serializers.ValidationError(message) def set_context(self, serializer_field): # 執行驗證以前調用,serializer_fields是當前字段對象
pass
class ModelUserSerializer(serializers.ModelSerializer): user = serializers.CharField(max_length=32)#額外的寫另一個字段,若是新寫的字段和表中某個字段相同則至關於重寫表字段
class Meta: model = models.UserInfo fields = "__all__" #能夠取表中所有字段,也能夠自定製取哪些字段
# fields = ['user', 'pwd', 'ut']
depth = 2 #深度查詢,意思就是說當一個表中有外鍵時,能夠查詢外鍵字段對應的表字段全部信息
extra_kwargs = {'user': {'min_length': 6}, 'pwd': {'validators': [PasswordValidator(666), ]}} # read_only_fields = ['user']
class TestView(APIView): def get(self, request, *args, **kwargs): # 序列化,將數據庫查詢字段序列化爲字典
data_list = models.UserInfo.objects.all() ser = ModelUserSerializer(instance=data_list, many=True) # 拿表中的多個或單個值,而後序列化成字符串返回給用戶
# obj = models.UserInfo.objects.all().first()
# ser = UserSerializer(instance=obj, many=False)
return Response(ser.data) def post(self, request, *args, **kwargs): # 驗證,對請求發來的數據進行驗證
print(request.data) ser = ModelUserSerializer(data=request.data) if ser.is_valid(): print(ser.validated_data) else: print(ser.errors) return Response('POST請求,響應內容')
c. 手動生成URL
from django.conf.urls import url, include from web.views.s6_serializers import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), url(r'detail/(?P<pk>\d+)/', TestView.as_view(), name='detail'), ]
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from .. import models class PasswordValidator(object): def __init__(self, base): self.base = str(base) def __call__(self, value): if value != self.base: message = 'This field must be %s.' % self.base raise serializers.ValidationError(message) def set_context(self, serializer_field): # 執行驗證以前調用,serializer_fields是當前字段對象
pass
class ModelUserSerializer(serializers.ModelSerializer): ut = serializers.HyperlinkedIdentityField(view_name='detail') #view_name指的是在路由系統的url中反向生成url的名稱,ut指代的是反向生成的url,可是必須在Serializer實例化的時候添加上context={'request': request}才能夠
class Meta: model = models.UserInfo fields = "__all__" extra_kwargs = { #自定義驗證規則
'user': {'min_length': 6}, 'pwd': {'validators': [PasswordValidator(666),]}, } depth=2 #會自動查找深度爲2的外鍵對象關係表中全部字段數據,而後把數據一併返回給客戶端
class TestView(APIView): def get(self, request, *args, **kwargs): # 序列化,將數據庫查詢字段序列化爲字典
data_list = models.UserInfo.objects.all() ser = ModelUserSerializer(instance=data_list, many=True, context={'request': request})#實例化產生一個對象,對象.data獲得字符串,再Response就是字符串序列化
# 或
# obj = models.UserInfo.objects.all().first()
# ser = UserSerializer(instance=obj, many=False)
return Response(ser.data) def post(self, request, *args, **kwargs): # 驗證,對請求發來的數據進行驗證
print(request.data) ser = ModelUserSerializer(data=request.data) if ser.is_valid(): print(ser.validated_data) else: print(ser.errors) return Response('POST請求,響應內容')
d. 自動生成URL
from django.conf.urls import url, include from web.views.s6_serializers import TestView urlpatterns = [ url(r'test/', TestView.as_view(), name='test'), url(r'detail/(?P<pk>\d+)/', TestView.as_view(), name='表名-detail'), ] #pk是本身字段id,這個name內必須寫 '代表-detail'
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from .. import models class PasswordValidator(object): def __init__(self, base): self.base = str(base) def __call__(self, value): if value != self.base: message = 'This field must be %s.' % self.base raise serializers.ValidationError(message) def set_context(self, serializer_field): # 執行驗證以前調用,serializer_fields是當前字段對象
pass
class ModelUserSerializer(serializers.HyperlinkedModelSerializer): #ll = serializers.HyperlinkedIdentityField(view_name='表名-detail') #能夠不用寫這兩個,由於他說自動幫咱們生成url
#tt = serializers.CharField(required=False)
class Meta: model = models.UserInfo fields = "__all__"#若是報錯則能夠寫chengfields=[user,pwd,url],其中url是程序自動生成的
list_serializer_class = serializers.ListSerializer extra_kwargs = { 'user': {'min_length': 6}, 'pwd': {'validators': [PasswordValidator(666), ]}, 'url': {'view_name': 'xxxx'}, 'ut': {'view_name': 'xxxx'}, } class TestView(APIView): def get(self, request, *args, **kwargs): # # 序列化,將數據庫查詢字段序列化爲字典
data_list = models.UserInfo.objects.all() ser = ModelUserSerializer(instance=data_list, many=True, context={'request': request}) # # 若是Many=True
# # 或
# # obj = models.UserInfo.objects.all().first()
# # ser = UserSerializer(instance=obj, many=False)
return Response(ser.data) def post(self, request, *args, **kwargs): # 驗證,對請求發來的數據進行驗證
print(request.data) ser = ModelUserSerializer(data=request.data) if ser.is_valid(): print(ser.validated_data) else: print(ser.errors) return Response('POST請求,響應內容')
八、分頁
a、根據頁碼進行分頁
from django.conf.urls import url, include from rest_framework import routers from web.views import s9_pagination urlpatterns = [ url(r'^test/', s9_pagination.UserViewSet.as_view()), ]
from rest_framework.views import APIView from rest_framework import serializers from .. import models from rest_framework.pagination import PageNumberPagination class StandardResultsSetPagination(PageNumberPagination): # 默認每頁顯示的數據條數
page_size = 1
# 獲取URL參數中設置的每頁顯示數據條數
page_size_query_param = 'page_size'
# 獲取URL參數中傳入的頁碼key
page_query_param = 'page' #127.0.0.1/pages?page=1,即獲取1這個數據
# 最大支持的每頁顯示的數據條數
max_page_size = 1
class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
class UserViewSet(APIView): def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().order_by('-id') # 實例化分頁對象,獲取數據庫中的分頁數據
paginator = StandardResultsSetPagination() page_user_list = paginator.paginate_queryset(user_list, self.request, view=self) # 序列化對象
serializer = UserSerializer(page_user_list, many=True) # 生成分頁和數據
response = paginator.get_paginated_response(serializer.data) #不只返回json後的數據還會生成上一頁的連接和下一頁的連接
return response
b、位置和個數進行分頁
from django.conf.urls import url, include from web.views import s9_pagination urlpatterns = [ url(r'^test/', s9_pagination.UserViewSet.as_view()), ]
from rest_framework.views import APIView from rest_framework import serializers from .. import models from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination class StandardResultsSetPagination(LimitOffsetPagination): # 默認每頁顯示的數據條數
default_limit = 10
# URL中傳入的顯示數據條數的參數
limit_query_param = 'limit'
# URL中傳入的數據位置的參數
offset_query_param = 'offset'
# 最大每頁顯得條數
max_limit = None class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
class UserViewSet(APIView): def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().order_by('-id') # 實例化分頁對象,獲取數據庫中的分頁數據
paginator = StandardResultsSetPagination() page_user_list = paginator.paginate_queryset(user_list, self.request, view=self) # 序列化對象
serializer = UserSerializer(page_user_list, many=True) # 生成分頁和數據
response = paginator.get_paginated_response(serializer.data) return response
c. 遊標分頁
from django.conf.urls import url, include from web.views import s9_pagination urlpatterns = [ url(r'^test/', s9_pagination.UserViewSet.as_view()), ]
from rest_framework.views import APIView from rest_framework import serializers from .. import models from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination class StandardResultsSetPagination(CursorPagination): # URL傳入的遊標參數
cursor_query_param = 'cursor'
# 默認每頁顯示的數據條數
page_size = 2
# URL傳入的每頁顯示條數的參數
page_size_query_param = 'page_size'
# 每頁顯示數據最大條數
max_page_size = 1000
# 根據ID從大到小排列
ordering = "id"
class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
class UserViewSet(APIView): def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().order_by('-id') # 實例化分頁對象,獲取數據庫中的分頁數據
paginator = StandardResultsSetPagination() page_user_list = paginator.paginate_queryset(user_list, self.request, view=self) # 序列化對象
serializer = UserSerializer(page_user_list, many=True) # 生成分頁和數據
response = paginator.get_paginated_response(serializer.data) return response
九、路由系統
a、自定義路由
from django.conf.urls import url, include from web.views import s11_render urlpatterns = [ url(r'^test/$', s11_render.TestView.as_view()), #普通url
url(r'^test\.(?P<format>\w+)$', s11_render.TestView.as_view()), #後面跟後綴的url,(test.json,test.admin等)
url(r'^test/(?P<pk>[^/.]+)/$', s11_render.TestView.as_view()), # url(r'^test/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view()) ]
from rest_framework.views import APIView from rest_framework.response import Response from .. import models class TestView(APIView): def get(self, request, *args, **kwargs): print(kwargs) #打印的是個字典,和{‘format’:‘...’}
print(self.renderer_classes) return Response('...')
b. 半自動路
from django.conf.urls import url, include from web.views import s10_generic urlpatterns = [ url(r'^test/$', s10_generic.UserViewSet.as_view({'get': 'list', 'post': 'create'})),#get請求對應的是list,查的是整個表數據,retrieve查的是個對象,post請求對應的是create,update請求對應的是update,delete請求對應的是destroy,
url(r'^test/(?P<pk>\d+)/$', s10_generic.UserViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})), ]
from rest_framework.viewsets import ModelViewSet from rest_framework import serializers from .. import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
class UserViewSet(ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = UserSerializer
c、全自動路由
from django.conf.urls import url, include from rest_framework import routers from web.views import s10_generic #先導入view中的繼承了ModelViewSet的那個類
router = routers.DefaultRouter() router.register('index', s10_generic) #index指代的是url的前綴,經過127.0.0.1/index/訪問全部數據,127.0.0.1/index/1/訪問id爲1的數據 # 註釋:只要router.register('index', s10_generic) 就會爲這個s10_generic類生成對應的四個url
#url(r'^test/$', s11_render.TestView.as_view()),
#url(r'^test\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view()),
#url(r'^test/(?P<pk>[^/.]+)/$', s11_render.TestView.as_view()),
#url(r'^test/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view())
urlpatterns = [ url(r'^', include(router.urls)), ]
from rest_framework.viewsets import ModelViewSet from rest_framework import serializers from .. import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
class UserViewSet(ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = UserSerializer 複製代碼
10. 視圖
a. GenericViewSet
from django.conf.urls import url, include from web.views.s7_viewset import TestView urlpatterns = [ url(r'test/', TestView.as_view({'get':'list'}), name='test'), url(r'detail/(?P<pk>\d+)/', TestView.as_view({'get':'list'}), name='xxxx'), ]
from rest_framework import viewsets from rest_framework.response import Response class TestView(viewsets.GenericViewSet): def list(self, request, *args, **kwargs): return Response('...') def add(self, request, *args, **kwargs): pass
def delete(self, request, *args, **kwargs): pass
def edit(self, request, *args, **kwargs): pass
b. ModelViewSet(自定義URL)
from django.conf.urls import url, include from web.views import s10_generic urlpatterns = [ url(r'^test/$', s10_generic.UserViewSet.as_view({'get': 'list', 'post': 'create'})), url(r'^test/(?P<pk>\d+)/$', s10_generic.UserViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})), ]
from rest_framework.viewsets import ModelViewSet from rest_framework import serializers from .. import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class UserViewSet(ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = UserSerializer
c. ModelViewSet(rest framework路由)
from django.conf.urls import url, include from rest_framework import routers from app01 import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^', include(router.urls)), ]
from rest_framework import viewsets from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Group fields = ('url', 'name') 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
十一、渲染器
根據 用戶請求URL 或 用戶可接受的類型,篩選出合適的 渲染組件。用戶請求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json
用戶請求頭:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
a. json
訪問URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json
http://127.0.0.1:8000/test
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from rest_framework.renderers import JSONRenderer from .. import models class TestSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class TestView(APIView): renderer_classes = [JSONRenderer, ] def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all() ser = TestSerializer(instance=user_list, many=True) return Response(ser.data)
b. 表格
訪問URL:
http://127.0.0.1:8000/test/?format=admin
http://127.0.0.1:8000/test.admin
http://127.0.0.1:8000/test/
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from rest_framework.renderers import AdminRenderer from .. import models class TestSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class TestView(APIView): renderer_classes = [AdminRenderer, ] def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all() ser = TestSerializer(instance=user_list, many=True) return Response(ser.data)
c. Form表單
訪問URL:
http://127.0.0.1:8000/test/?format=form
http://127.0.0.1:8000/test.form
http://127.0.0.1:8000/test/
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from rest_framework.renderers import JSONRenderer from rest_framework.renderers import AdminRenderer from rest_framework.renderers import HTMLFormRenderer from .. import models class TestSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class TestView(APIView): renderer_classes = [HTMLFormRenderer, ] def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().first() ser = TestSerializer(instance=user_list, many=False) return Response(ser.data)
d. 自定義顯示模板
訪問URL:
http://127.0.0.1:8000/test/?format=html
http://127.0.0.1:8000/test.html
http://127.0.0.1:8000/test/
from django.conf.urls import url, include from web.views import s11_render urlpatterns = [ url(r'^test/$', s11_render.TestView.as_view()), url(r'^test\.(?P<format>[a-z0-9]+)', s11_render.TestView.as_view()), ]
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from rest_framework.renderers import TemplateHTMLRenderer from .. import models class TestSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class TestView(APIView): renderer_classes = [TemplateHTMLRenderer, ] def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().first() ser = TestSerializer(instance=user_list, many=False) return Response(ser.data, template_name='user_detail.html')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ user }} {{ pwd }} {{ ut }} </body> </html>
e. 瀏覽器格式API+JSON
訪問URL:
http://127.0.0.1:8000/test/?format=api
http://127.0.0.1:8000/test.api
http://127.0.0.1:8000/test/
#!/usr/bin/env python # -*- coding:utf-8 -*- from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import serializers from rest_framework.renderers import JSONRenderer from rest_framework.renderers import BrowsableAPIRenderer from .. import models class TestSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class CustomBrowsableAPIRenderer(BrowsableAPIRenderer): def get_default_renderer(self, view): return JSONRenderer() class TestView(APIView): renderer_classes = [CustomBrowsableAPIRenderer, ] def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all().first() ser = TestSerializer(instance=user_list, many=False) return Response(ser.data, template_name='user_detail.html') 複製代碼
注意:若是同時多個存在時,自動根據URL後綴來選擇渲染器。
總結1: RESTful的執行流程
一、用戶請求到達路由系統-----路由系統經過as_view()找到dispatch方法
二、dispatch方法對request數據進行二次封裝,request數據的二次分裝以後獲得的是個對象列表,而後把每個對象(對象列表是從renderer_classes,parser_classes,authentication_classes,
throttle_classes,permission_classes,versioning_class類中拿的,若是咱們在視圖類函數中沒有重寫該類方法,就會走默認的類下的方法。)列表賦值給request
三、執行initial方法,該方法主要是處理版本,認證,權限,節流等相關操做,主要是執行對象下的等相關類下的方法,也就是在第二步爲咱們分裝好了的方法。
四、根據反射找到對應的類(本身寫的類方法)而後實例化執行類,獲得response返回值,而後返回這個返回值給客戶端
五、執行流程如圖所示:咱們手動的操做主要是在步驟二中進行,即在view中重寫他所提供的默認的類方法,執行完步驟三就至關於將認證相關的方法和調用相關的方法都封裝到了request中
總體流程 第三部initial流程
總結2:
0、version方法直接配置全局或者局部參數便可
一、authentication方法只須要返回一個元組表示認證經過,返回一個None表示匿名用戶登錄,觸發一個異常表示認證不經過
二、permissions方法返回一個True表示有權訪問,返回一個Flase表示武器訪問
三、throttling方法返回一個True則能夠訪問,若是爲Flase則不能夠訪問
總結3:RESTful中視圖類的繼承關係