from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
class AuthThrottle(MiddlewareMixin):
VISIT_RECORD = {}
history = None
def allow_request(self, request):
ip = request.META.get('REMOTE_ADDR')
import time
ctime = time.time()
if ip not in self.VISIT_RECORD:
self.VISIT_RECORD[ip] = [ctime, ]
return True
self.history = self.VISIT_RECORD.get(ip)
while self.history and ctime - self.history[-1] > 60:
self.history.pop()
if len(self.history) < 5:
self.history.insert(0, ctime)
return True
else:
return False
def wait(self):
import time
ctime = time.time()
msg = 60 - (ctime - self.history[-1])
return msg
import json
def process_request(self, request):
if self.allow_request(request):
pass
else:
msg = self.wait()
msg = str(msg)[0:2]
return JsonResponse({"code": 101, "msg": '我在中间件拦的你啊DSB还差%s秒才能执行' % msg},json_dumps_params={'ensure_ascii':False})
标签:ctime,验证,中间件,self,request,time,msg,history
From: https://www.cnblogs.com/tzmy/p/16864767.html