Django-restframework 之頻率原始碼分析
Django-restframework 之頻率原始碼分析
一 前言
經過許可權判斷之後就是進行頻率的判斷了,而頻率的判斷和許可權又不一樣,認證、許可權和頻率的執行流程都差不多,使用配置裡面的相關類來進行判斷。而不和認證和許可權一樣,頻率的配置沒有,檢視 APIView
的類屬性如下:
二 頻率元件執行流程
雖然 restframework
原生滅有配置頻率,但是提供了幾個進行頻率判斷的類,如下:
其中 SimpleRateThrottle
類是根據訪問者 ip 來進行頻率限制的一個類,來看看這個類的執行流程。
1. init方法
2. get_rate
3. 執行 allow_request方法
4. get_cache_key
5. 時間差判斷
6. throttle_success
認證失敗的話執行 throttle_failure
,其實就是返回 False
。
7. wait
三 自定義頻率元件
1. 自定義頻率類
頻率類需要繼承自帶的頻率類
# from rest_framework.throttling import BaseThrottle class BookThrottle(BaseThrottle): VISIT_RECORD = {} def __init__(self): self.history = None def allow_request(self, request, view): print(request.META) REMOTE_ADDR = request.META.get('REMOTE_ADDR') import time ctime = time.time() if REMOTE_ADDR not in self.VISIT_RECORD: self.VISIT_RECORD[REMOTE_ADDR] = [ctime,] return True self.history = self.VISIT_RECORD.get(REMOTE_ADDR) while self.history and ctime - self.history[-1] > 60: self.history.pop() if len(self.history) < 3: self.history.insert(0, ctime) return True else: return False def wait(self): import time ctime = time.time() return 60 - (ctime - self.history[-1])
# 頻率類程式碼註釋 # 訪問頻率的邏輯 ##{'ip地址':[16:13:39,16:13:19,],'ip地址2':[時間1,時間2],} ## (1)取出訪問者ip ## (2)判斷當前ip不在訪問字典裡,新增進去,並且直接返回True,表示第一次訪問,在字典裡,繼續往下走 ## (3)迴圈判斷當前ip的列表,有值,並且當前時間減去列表的最後一個時間大於60s,把這種資料pop掉,這樣列表中只有60s以內的訪問時間, ## (4)判斷,當列表小於3,說明一分鐘以內訪問不足三次,把當前時間插入到列表第一個位置,返回True,順利通過 ## (5)當大於等於3,說明一分鐘內訪問超過三次,返回False驗證失敗 ##(1)取出訪問者ip ## print(request.META) ## REMOTE_ADDR 就是訪問者的ip:127.0.0.1 #ip=request.META.get('REMOTE_ADDR') #import time ## 獲取當前時間 #ctime=time.time() ## (2)判斷當前ip不在訪問字典裡,新增進去,並且直接返回True,表示第一次訪問 #if ip not in self.VISIT_RECORD: #self.VISIT_RECORD[ip]=[ctime,] ## {'127.0.0.1':[時間1,時間1,]} #return True ## self.history=[時間1,時間1,] #self.history=self.VISIT_RECORD.get(ip) ## (3)迴圈判斷當前ip的列表,有值,並且當前時間減去列表的最後一個時間大於60s,把這種資料pop掉,這樣列表中只有60s以內的訪問時間, #while self.history and ctime-self.history[-1]>60: #self.history.pop() ## (4)判斷,當列表小於3,說明一分鐘以內訪問不足三次,把當前時間插入到列表第一個位置,返回True,順利通過 ## (5)當大於等於3,說明一分鐘內訪問超過三次,返回False驗證失敗 #if len(self.history)<3: #self.history.insert(0,ctime) #return True #else: #return False
2. 使用
使用很簡單,在需要進行頻率控制的檢視類中定義一個屬性 throttle_classes
,如下:
class Book(APIView): authentication_classes = [authticate_classes.BookAuth] permission_classes = [permiss_classes.LoginPermission] throttle_classes = [thrott_classes.BookThrottle] # authentication_classes = [] def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, id): print(request.user, '444') response = {'status': 100, 'msg': None} book_obj = models.Book.objects.filter(pk=id).first() if book_obj: book_ser = myser.BookSer(book_obj, many=False) response['book'] = book_ser.data else: response['msg'] = '圖書沒有物件' response['status'] = 101 return Response(response)
四 配置自定義頻率類
1. 區域性配置
其實上面的就是區域性配置,
class Book(APIView): authentication_classes = [authticate_classes.BookAuth] permission_classes = [permiss_classes.LoginPermission] throttle_classes = [thrott_classes.BookThrottle]
2. 全域性使用
全域性配置如下:
REST_FRAMEWORK={ 'DEFAULT_THROTTLE_CLASSES': ['app01.thrott_classes.BookThrottle'] }
3. 區域性禁用
區域性禁用需要在檢視類中定義一個空的 throttle_classes
屬性
throttle_classes = []