Django rest framework源碼分析(3)----節流 添加節流 自定義節流的方法 限制60s內只能訪問3次 (1)API文件夾下面新建throttle.py,代碼如下: # utils/throttle.py from rest_framework.throttling import BaseThrottle import time VISIT_RECORD = {} #保存訪問記錄 class VisitThrottle(BaseThrottle): '''60s內只能訪問3次''' def __init__(self): self.history = None #初始化訪問記錄 def allow_request(self,request,view): #獲取用戶ip (get_ident) remote_addr = self.get_ident(request) ctime = time.time() #如果當前IP不在訪問記錄裏面,就添加到記錄 if remote_addr not in VISIT_RECORD: VISIT_RECORD[remote_addr] = [ctime,] #鍵值對的形式保存 return True #True表示可以訪問 #獲取當前ip的歷史訪問記錄 history = VISIT_RECORD.get(remote_addr) #初始化訪問記錄 self.history = history #如果有歷史訪問記錄,並且最早一次的訪問記錄離當前時間超過60s,就刪除最早的那個訪問記錄, #只要為True,就一直循環刪除最早的一次訪問記錄 while history and history[-1] < ctime - 60: history.pop() ...