中間件:一個用戶1分鐘訪問不能超過3次
阿新 • • 發佈:2018-08-11
elf pro print n) {} ins ros pan tor
now = time.time()
# 3. 記錄訪問的歷史
if ip not in VISIT_RECORD:
VISIT_RECORD[ip] = []
history = VISIT_RECORD[ip]
# [11:07:20, 10:07:11, 10:07:06, 10:07:01]
#當本次訪問與之前的訪問超過60s,則清除之前的訪問記錄
while history and now - history[-1] > 10:
history.pop()
# 判斷用戶在一分鐘的時間間隔內是否訪問超過3次
if len(history) >= 3:
return HttpResponse("訪問過於頻繁...")
#把新的訪問記錄添加在列表的第一個
history.insert(0, now)
# 定義一個 訪問記錄的大字典 VISIT_RECORD = {} # 自定義一個訪問頻率限制的中間件 class Throttle(MiddlewareMixin): def process_request(self, request): # 1. 拿到用戶請求的IP # print(request.META) ip = request.META.get("REMOTE_ADDR") # 2. 當前請求的時間
#導入模塊
from django.utils.deprecation import MiddlewareMixin
中間件:一個用戶1分鐘訪問不能超過3次