列表從後往前讀#1.在request中獲取IP#2.訪問記錄VISIT_RECORD = {} 放緩存 數據庫 均可以 建議緩存import timeclass VisitThrottle(object): """10s內只能訪問3次""" def __init__(self): self.history = None def allow_request(self, request, view): #1.在request中獲取IP #2.訪問記錄 #remote_addr = request._request.META.get('REMOTE_ADDR') remote_addr = request.META.get("REMOTE_ADDR") #均可以 ctime = time.time() if remote_addr not in VISIT_RECORD: VISIT_RECORD[remote_addr] = [ctime,] history = VISIT_RECORD.get(remote_addr) self.history = history while history and history[-1] < ctime - 10: history.pop() if len(history) < 3: history.insert(0, ctime) return True return True #表示能夠繼續訪問 #return False #訪問頻率過高,被限制 def wait(self): """還須要等多少秒""" ctime = time.time() data = 60 - (ctime - self.history[-1]) return datathrottle_classes = [VisitThrottle,]#全局配置REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle']}源碼流程 check_throttles self.get_throttles內置函數from rest_framework.throttling import BaseThrottleclass BaseThrottle(object): def allow_request(self,request, view) #由這個函數進行觸發 def get_ident(self,request): def wait(self):到時可使用SimpleRateThrottlefrom rest_framework.throttling import SimpleRateThrottleclass VisiThrottle(SimpleRateThrottle): scope = "xiao" #當KEY使用 當在setting設置DEFAULT_THROTTLE_RATES : {"xiao":'3/m'} m分 h時 d天 def get_cache_key(self, request, view): return request.META.get("REMOTE_ADDR")class VIPThrottle(SimpleRateThrottle): scope = "vip" #當KEY使用 當在setting設置DEFAULT_THROTTLE_RATES : {"xiao":'3/m'} m分 h時 d天 def get_cache_key(self, request, view): return request.user.username #認證時的對象的usernameSettings裏面添加REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":['cmdb.utils.throttle.Visit2Throttle'], #此時不能在這裏添加兩個控制 "DEFAULT_THROTTLE_RATES": { "xiao": '3/m', "vip":'10/m', #vip用戶訪問頻率限制}}基本使用 類 繼承:BaseThrottle 實現:allow_request, wait 類 繼承:SimpleRateThrottle 實現:get_cache_key 、 scope = "xiao" (配置文件中的key)