1. APIView的dispath方法中的self.initial(request, *args, **kwargs) 點進去 2. self.check_throttles(request) # 進行頻率驗證 # 頻率組件核心源碼分析 def check_throttles(self, request): throttle_durations = [] # 1. 遍歷配置的頻率認證類,初始化獲得一個個頻率認證類對象(會調用頻率認證類的__init__()方法) # 2. 頻率認證類對象調用allow_request方法,判斷是否限次(沒有限次可訪問,限次不可訪問) # 3. 頻率認證類對象再限次後,調用wait方法, 獲取還需等待多長的時間能夠進行下一次訪問 # 頻率認證類都是繼承 SimpleRateThrottles類 for throttle in self.get_throttles(): if not throttle.allow_request(request, self) # 只要頻率限制了,allow_request 返回False了, 纔會調用wait throttle_durations.append(throttle.wait()) if throttle_durations: durations=[ duration for duration in throttle_durations if duration is not None] duration = max(durations, default=None) self.throttled(request, duration)
1. 自定義一個繼承SimpleRateThrottle類的頻率類 2. 設置一個scope類屬性, 屬性值爲任意見名知意的字符串 3. 在settings配置文件中,配置drf的DEFAULT_THROTTLE_RATES, 格式爲{scope字符串:'次數/時間'} 4. 在自定義頻率類中重寫get_cache_key方法 # 限制的對象返回,與限制信息有關的字符串 # 不限制的對象返回None(只能放回None, 不能是False或者是''等)
短信接口1/min頻率限制git
頻率: api/throttles.pygithub
from rest_framework.throttling import SimpleRateThrottle class SMSRateThrottle(SimpleRateThrottle): scope = 'sms' # 只對提交手機號的get方法進行限制 def get_cache_key(self, request, view): mobile = request.query_params.get('mobile') # 沒有手機號, 就不作頻率限制 if not mobile: return None # 返回能夠根據手機號動態變化,且不易重複的字符串,做爲操做緩存的key return 'throttle_%(scope)s_%(ident)s' %{'scope': self.scope, 'ident': mobile}
配置: settings.py算法
drf 配置 REST_FRAMEWORK = { # 頻率限制條件配置 'DEFAULT_THROTTLE_RATES': { 'sms': '1/min'}, }
視圖; views.py數據庫
from . throttles import SMSRateThrottle class TestSMSAPIView(APIView): # 局部配置頻率認證 throttle_classes = [SMSRateThrottle] def get(self, request, *args, **kwargs): return APIResponse(0, 'get 獲取驗證碼') def post(self, request, *args, **kwargs): return APIResponse(0, 'post 獲取驗證碼')
路由:api/url.pydjango
url(r'^sms/$', views.TestSMSAPIView.as_view())
限制的接口json
只會對/api/sms/?mobile=具體手機號 接口才會有頻率限制 1. 對api/sms/ 或其餘接口發送無限制 2. 對數據包提交mobile的api/sms接口無限制 3. 對不是mobile(如phone)字段提交的電話接口無限制
drf分類api
數據庫session認證: 低效緩存
緩存認證:高效服務器
jwt認證: 高效session
緩存認證:不容易併發
jwt認證: 容易併發
優勢:
1) 服務器不要存儲token,token交給每個客戶端本身存儲,服務器壓力小 2)服務器存儲的是 簽發和校驗token 兩段算法,簽發認證的效率高 3)算法完成各集羣服務器同步成本低,路由項目完成集羣部署(適應高併發)
格式:
1) jwt token採用三段式:頭部.載荷.簽名 2)每一部分都是一個json字典加密形參的字符串 3)頭部和載荷採用的是base64可逆加密(前臺後臺均可以解密) 4)簽名採用hash256不可逆加密(後臺校驗採用碰撞校驗) 5)各部分字典的內容: 頭部:基礎信息 - 公司信息、項目組信息、可逆加密採用的算法 載荷:有用但非私密的信息 - 用戶可公開信息、過時時間 簽名:頭部+載荷+祕鑰 不可逆加密後的結果 注:服務器jwt簽名加密祕鑰必定不能泄露 簽發token:固定的頭部信息加密.當前的登錄用戶與過時時間加密.頭部+載荷+祕鑰生成不可逆加密 校驗token:頭部可校驗也能夠不校驗,載荷校驗出用戶與過時時間,頭部+載荷+祕鑰完成碰撞檢測校驗token是否被篡改
drf_jwt插件
官網
https://github.com/jpadilla/django-rest-framework-jwt
安裝
>: pip3 install djangorestframework-jwt
登陸- 簽發token: api/urls.py
# ObtainJSONWebToken視圖類就是經過username和password獲得user對象而後簽發token from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token urlpatterns = [ # url(r'^jogin/$', ObtainJSONWebToken.as_view()), url(r'^jogin/$', obtain_jwt_token), ]
認證-校驗token: 全局或局部配置drf_jwt的認證類
from rest_framework.views import APIView from utils.response import APIResponse # 必須登陸後才能訪問 - 經過了認證權限組件 from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication class UserDetail(APIView): authentication_classes = [JSONWebTokenAuthentication] # jwt-token校驗request.user permission_classes = [IsAuthenticated] # 結合權限組件篩選掉遊客 def get(self, request, *args, **kwargs): return APIResponse(results={'username': request.user.username})
路由與接口測試
# 路由 url(r'^user/detail/$', views.UserDetail.as_view()), # 接口:/api/user/detail/ # 認證信息:必須在請求頭的 Authorization 中攜帶 "jwt 後臺簽發的token" 格式的認證字符串