Django中间件限制高频率访问

两种方式实现

1 使用最后时间判断

class Throttle(MiddlewareMixin):
    VIEW_LIMIT = {}
    def process_request(self,requst):
        # 限制访问次数
        # 1分钟内只允许访问3次
        remote_addr = requst.META['REMOTE_ADDR']
        print(self.VIEW_LIMIT)
        if remote_addr not in self.VIEW_LIMIT:
            self.VIEW_LIMIT[remote_addr] = {
                "count":1,
                "limit_time": datetime.datetime.now()+datetime.timedelta(minutes=1), #下一分钟
            }
            # print(self.VIEW_LIMIT)
        else:
            # 访问次数判断
            count = self.VIEW_LIMIT[remote_addr]["count"];
            # count = count+1
            # self.VIEW_LIMIT[remote_addr]["count"] = count
            # print(self.VIEW_LIMIT)
            # 判断时间和次数
            now = datetime.datetime.now()
            if count>3 and now<=self.VIEW_LIMIT[remote_addr]["limit_time"]:
                # 限制访问
                print("拒绝访问")
                return HttpResponse("访问限制!")
            else:
                if now>self.VIEW_LIMIT[remote_addr]["limit_time"]:
                    # 重新设置ip 访问
                    self.VIEW_LIMIT[remote_addr] = {
                        "count": 1,
                        "limit_time": datetime.datetime.now() + datetime.timedelta(minutes=1),
                    }
                else:
                    # 一分钟内, 次数+1
                    self.VIEW_LIMIT[remote_addr]['count'] = count+1

2 使用访问历史判断

import time
class HistoryThrottle(MiddlewareMixin):
    VISIT_DICT = {}
    def process_request(self,request):
        # 记录访问历史
        remote_ip = request.META.get('REMOTE_ADDR')
        if not self.VISIT_DICT.get(remote_ip):
            self.VISIT_DICT[remote_ip]= []
        history = self.VISIT_DICT[remote_ip]
        history_new = []
        now =time.time()
        for k in history:
            if now-k<=60:
                history_new.append(k)
        #清空数组
        del history[:]
        history_new.append(now)
        self.VISIT_DICT[remote_ip] = history_new
        if len(history_new)>3:
            print("拒绝访问")
            return HttpResponse("访问限制!")

        print(self.VISIT_DICT)

原文链接: Django中间件限制高频率访问 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-657.html )

发表评论

0则评论给“Django中间件限制高频率访问”