自定義頻率類
阿新 • • 發佈:2020-07-11
自定義頻率元件
from rest_framework.throttling import BaseThrottle class MyThrottles(BaseThrottle): # 由ip跟時間列表組成的字典 VISIT_RECORD = {} def __init__(self): # 用來記錄已經訪問過的ip的時間列表 self.history = None # 重寫allow_request方法 def allow_request(self, request, view): # 獲取ip ip = request.META.get('REMOTE_ADDR') print(ip) # 獲取當前時間作為ip第一次訪問時間 ctime = time.time() # ip不在字典中就新增,並返回通過 if ip not in self.VISIT_RECORD: self.VISIT_RECORD[ip] = [ctime, ] return True # 獲取ip對應的時間列表賦值給history self.history = self.VISIT_RECORD.get(ip) # 迴圈時間列表,將列表中時間大於1分鐘的全部剔除,保證self.history中的訪問時間是1分鐘內的 while self.history and ctime - self.history[-1] > 60: self.history.pop() # 判斷時間列表的長度,限制同一個ip1分鐘內的訪問次數 if len(self.history) < 5: self.history.insert(0, ctime) return True return False # ip被限制後的等待時間 def wait(self): nonw_time = time.time() wait_time = 60 - (nonw_time - self.history[-1]) return wait_time
自定義頻率元件使用
區域性使用
# 在檢視類中設定
throttle_classes = [MyThrottles, ]
全域性使用
# 在settings.py檔案中設定如下程式碼,可以設定多個
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': ('work.user_auth.MyThrottles',)
}