基于中间件访问频率限制 每分钟时间间隔最多访问3次

同一个IP 1分钟时间间隔只能访问三次

1. 拿到用户请求的IP
2. 当前请求的时间
3. 记录访问的历史
VISIT_RECORD ={
    'ip':[]
}
class Throttle(MiddlewareMixin):
    def process_request(self,request):
        # print(request.META)通过这个可以拿到ip
        ip = request.META.get('REMOTE_ADDR')
        now = time.time()
        if ip not in VISIT_RECORD:
            VISIT_RECORD[ip] = []
        history = VISIT_RECORD[ip]
        while history and now - history[-1] >60:
            history.pop()
        if len(history) >= 3:
            return HttpResponse('您的访问次数超出限制!请在一分钟之后再次访问!!!')
        history.insert(0,now)

猜你喜欢

转载自www.cnblogs.com/hnlmy/p/10632521.html