django DRF请求访问频率限制

Django REST framework(DRF)提供了一个throttle_classes属性,可以用于限制API的访问频率。它可以防止恶意用户发送大量请求以消耗服务器资源。

使用throttle_classes属性,需要在settings.py中配置REST_FRAMEWORK

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle', # 匿名用户访问频率限制
        'rest_framework.throttling.UserRateThrottle', # 登录用户访问频率限制
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day', # 匿名用户每天最多100次请求
        'user': '1000/day', # 登录用户每天最多1000次请求
    }
}

这里使用了两个默认的限制类:AnonRateThrottleUserRateThrottleAnonRateThrottle用于限制匿名用户的访问频率,UserRateThrottle用于限制登录用户的访问频率。

DEFAULT_THROTTLE_RATES中,我们可以为每个限制类指定一个速率限制,例如'anon': '100/day'表示每天匿名用户最多可以发送100个请求。

如果需要自定义限制类,可以继承throttling.SimpleRateThrottle类并实现allow_request()get_cache_key()方法。例如:

from rest_framework.throttling import SimpleRateThrottle

classCustomThrottle(SimpleRateThrottle):
    rate = '10/hour'# 每小时最多10次请求
    def get_cache_key(self, request, view):
        return self.get_ident(request) # 使用IP地址作为缓存key
    def allow_request(self, request, view):
        ifnot self.rate:
            return True

        self.key = self.get_cache_key(request, view)
        if self.key isNone:
            return True

        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()

        if len(self.history) >= self.num_requests:
            return False

        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True

在上面的例子中,我们定义了一个名为CustomThrottle的限制类,它每小时最多允许10次请求。get_cache_key()方法返回一个缓存key,这里使用了请求的IP地址。allow_request()方法用于判断当前请求是否允许访问,如果超过了限制次数,则返回False,否则返回True

然后在视图类中使用throttle_classes属性指定限制类即可:

from rest_framework.throttling import AnonRateThrottle
from myapp.throttling import CustomThrottle
classMyView(APIView):
    throttle_classes = [AnonRateThrottle, CustomThrottle]

    def get(self, request):
        # ...

在上面的例子中,我们指定了两个限制类:AnonRateThrottleCustomThrottle,它们分别用于限制匿名用户和所有用户的访问频率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LINGK98

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值