django中间件控制访问频率

实现方式1

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import time


class User(object):
    def __init__(self, ip):
        self.ip = ip
        self.reset()

    def reset(self):
        self.first_time = time.time()
        self.counter = 1
        self.is_forbidden = False

# {ip:User()}
user_dict = {}


class TrafficMiddleware(MiddlewareMixin):
    def process_request(self, request):
        remote_ip = request.META.get('REMOTE_ADDR')
        if remote_ip not in user_dict:
            # 用户首次访问
            user_dict[remote_ip] = User(remote_ip)
        else:
            user_obj = user_dict.get(remote_ip)
            if not user_obj.is_forbidden:
                # 没有被限制时
                user_obj.counter += 1
                if user_obj.counter >= 10:
                    duration_time = time.time() - user_obj.first_time
                    user_obj.is_forbidden = True if duration_time < 60 else False
                if user_obj.is_forbidden:
                    user_obj.last_time = time.time()
                    return HttpResponse('访问频率过高,限制访问')
            else:
                # 被限制的需要等待1min后才能访问
                waited_time = time.time() - user_obj.last_time
                if waited_time >= 60:
                    user_obj.reset()
                else:
                    return HttpResponse('访问频率过高,限制访问')

实现方式2

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import time



user_dict = {}


class TrafficMiddleware(MiddlewareMixin):
    def process_request(self, request):
        remote_ip = request.META.get('REMOTE_ADDR')
        if remote_ip not in user_dict:
            user_dict[remote_ip] = [time.time(), 0]
        else:
            user_dict[remote_ip][1] += 1
            if time.time() - user_dict[remote_ip][0] <= 60 and user_dict[remote_ip][1] >= 10:
                return HttpResponse('刷新频率过高,限制登陆')
posted @ 2020-07-03 15:22  the3times  阅读(240)  评论(0编辑  收藏  举报