django 自定义中间件实现访问频率限制和IP禁用

由于Http请求是无状态的,服务端能直知道是那个客户端的访问,所以,我们可以利用session技术,记住每个用户访问的状态数据。

  • 在用户发起请求后,记录用户IP, 同时进行每次访问时间的统计,实现客户端的访问频率限制,IP禁止。
import time
from django.http import HttpResponse

# Create your views here.
VISIT_LIMIT = 20
TIME_INTERVAL = 10
RETRY_TIME = 10
IP_BLACKLIST = ["192.168.1.2", "127.0.0.1"]

class LimitMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # 处理请求前(url匹配前)调用
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        now = time.time()
        print("处理请求前(url匹配前)调用",now)
        request_queue 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值