Django-中间件实现1分钟内只允许三次访问
代码
class Throttle(MiddlewareMixin): def process_request(self, request): # 1. 拿到用户请求的IP # print(request.META) ip = request.META.get("REMOTE_ADDR") # 2. 当前请求的时间 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] while history and now - history[-1] > 10: history.pop() # 判断用户在一分钟的时间间隔内是否访问超过3次 if len(history) >= 3: return HttpResponse("滚...") history.insert(0, now)