import time
from django.shortcuts import render, HttpResponse
from django.utils.deprecation import MiddlewareMixin
visit_dict = {}
class Throttle(MiddlewareMixin):
def process_request(self, request):
# 获取IP
ip = request.META.get('REMOTE_ADDR')
now = time.time()
# 访问记录
if not visit_dict.get(ip):
visit_dict[ip] = []
history = visit_dict[ip]
# 方法一
# l = []
# for i in history:
# if now-i < 5:
# l.append(i)
# visit_dict[ip] = l
# history = visit_dict[ip]
# 方法二
while history and now-history[-1]>5:
history.pop()
# 根据访问记录做判断
if len(history) > 2 :
return HttpResponse('您的访问频率过快,请稍后')
history.insert(0, now)