django Throttling 节流 限制接口访问次数

Throttling

#0 GitHub

https://github.com/Coxhuang/dajngo-Throttling

#1 环境

Python3.6
Django==2.0.6
djangorestframework==3.8.2

#2 需求分析

  • 给客户开发一个后端接口,但是客户不是VPI会员,每天只能访问该接口10次,这时候节流就可以排上用场啦
  • 用户访问登录接口,要求用户在一分钟内访问超过3次,需要输入验证码,这时候,也可以使用节流

#3 什么是节流

限制类似于权限,因为它确定是否应该授权请求。Throttles表示临时状态,用于控制客户端可以对API发出的请求的速率。

#4 官方提供的节流库

#4.1 开始

新建一个Django项目
settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'app',
]
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle', # 匿名用户节流
        'rest_framework.throttling.UserRateThrottle' # 登录用户节流
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '2/m', # 匿名用户对应的节流次数
        'user': '5/m' # 登录用户对应 的节流次数
    }
}
views.py
from rest_framework.throttling import UserRateThrottle
from rest_framework.throttling import AnonRateThrottle

class view(mixins.ListModelMixin,GenericViewSet):

    throttle_classes = (UserRateThrottle,)  # 登录用户节流
    serializer_class = viewSerializer
    queryset = models.UserProfile.objects.all()
    
AnonRateThrottle:用户未登录请求限速,通过IP地址判断

UserRateThrottle:用户登陆后请求限速,通过token判断

注意:
如果在settings.py中设置有 UserRateThrottle / AnonRateThrottle 那么在所有接口函数中,都默认使用AnonRateThrottle节流,即,即使在接口中没有使用节流,也默认是AnonRateThrottle节流,只有在每个接口中加上
throttle_classes = () 才认为接口没有使用节流

#4.2 改进

为什么要自定义节流: 因为官方提供的节流,导致每一个接口都会使用,如果不使用,还需要设置为空throttle_classes = (), 这样会很麻烦

settings.py

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        # 'rest_framework.throttling.AnonRateThrottle',
        # 'rest_framework.throttling.UserRateThrottle'
        'rest_framework.throttling.ScopedRateThrottle',  # throttle_scope = 'uploads'
    ),
    'DEFAULT_THROTTLE_RATES': {
        # 'anon': '2/m',
        # 'user': '5/m'
        'uploads': '7/m',
    }
}

view.py

    throttle_scope = "uploads"

这样,像在哪个接口添加节流,直接添加,步添加的接口也不需要设置就留为空

#5 自定义节流

#5.1 需求分析
  • 登录时,密码错误三次,需要输入验证码
#5.2 新建文件 throttling.py
from __future__ import unicode_literals

from rest_framework.throttling import BaseThrottle,SimpleRateThrottle

COUNT = 0
class ScopedRateThrottle(SimpleRateThrottle):
    """
    自定义节流,节流不会限制访问,使用时,需要配合getCaptchasStatus()使用,当用户访问超出时,getCaptchasStatus返回False
    """
    scope_attr = 'throttle_no_scope'
    def __init__(self):
        pass

    def allow_request(self, request, view):
        global COUNT
        self.scope = getattr(view, self.scope_attr, None)
        if not self.scope:
            return True
        self.rate = self.get_rate()
        self.num_requests, self.duration = self.parse_rate(self.rate)
        ret = super(ScopedRateThrottle, self).allow_request(request, view)
        if not ret:
            COUNT = 1
        else:
            COUNT = 0
        return True

    def get_cache_key(self, request, view):
        """
        If `view.throttle_scope` is not setmail, don't apply this throttle.

        Otherwise generate the unique cache key by concatenating the user id
        with the '.throttle_scope` property of the view.
        """
        if request.user.is_authenticated:
            ident = request.user.pk
        else:
            ident = self.get_ident(request)

        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }


def getCaptchasStatus():
    if COUNT == 1:
        return True
    else:
        return False

#5.3 settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        # 'rest_framework.throttling.AnonRateThrottle',
        # 'rest_framework.throttling.UserRateThrottle'
        "app.throttling.ScopedRateThrottle",  # 自定义节流  throttle_no_scope = 'uploads'
    ),
    'DEFAULT_THROTTLE_RATES': {
        # 'anon': '2/m',
        # 'user': '5/m'
        'myThrottlingChackCaptchas': '3/m',  # 限制请求验证码次数

    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django1.8 中,我们可以通过使用 Redis 来实现接口访问频率限制。具体实现步骤如下: 1. 首先,在 settings.py 文件中配置 Redis: ``` CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } ``` 2. 在 views.py 文件中定义装饰器: ``` from django.core.cache import cache from django.http import HttpResponseBadRequest def rate_limit(key_prefix, rate, block=False): def decorator(view_func): def wrapper(request, *args, **kwargs): # 计算 key key = '{0}:{1}'.format(key_prefix, request.META['REMOTE_ADDR']) # 获取当前时间 now = int(time.time()) # 获取 key 对应的数据 data = cache.get(key) if not data: # 如果 key 对应的数据不存在,说明还没有访问过,直接存储当前时间 cache.set(key, '{0}:1'.format(now), rate) else: # 否则,将数据分解成时间戳和计数器 timestamp, count = data.split(':') # 如果当前时间戳减去存储的时间戳大于限制时间,则重置计数器和时间戳 if now - int(timestamp) > rate: cache.set(key, '{0}:1'.format(now), rate) else: # 否则,将计数器加1 count = int(count) + 1 cache.set(key, '{0}:{1}'.format(timestamp, count), rate) # 如果计数器大于限制次数,则返回错误信息 if count > rate: if block: return HttpResponseBadRequest('Rate limit exceed.') else: return HttpResponseBadRequest('Rate limit exceed. Retry after {0} seconds.'.format(int(timestamp) + rate - now)) return view_func(request, *args, **kwargs) return wrapper return decorator ``` 3. 在需要进行频率限制的视图函数上使用装饰器: ``` @rate_limit('api', 10, block=True) def my_view(request): # 处理请求 pass ``` 其中,`'api'` 是 key 的前缀,`10` 是限制时间(秒),`block=True` 表示超过限制次数时阻塞请求,否则返回错误信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值