美文网首页
rest_framework 访问频率控制

rest_framework 访问频率控制

作者: eeert2 | 来源:发表于2020-03-04 12:58 被阅读0次

一、访问频率控制的使用

  • 1.创建自己的频率控制类,继承BaseThrottle
class MyThrottling(throttling.BaseThrottle):

    def allow_request(self, request, view):
        # 返回 True,则表示可以继续访问
        # 返回 False,则表示访问频率过高,进行限制

        # 这里通过IP进行限制,60秒内只能访问3次
        remote_addr = request.META.get('REMOTE_ADDR')
        history: list = remote_dict.get(remote_addr, None)
        ctime = time.time()
        if not history:  # 初次访问

            remote_dict[remote_addr] = [ctime, ]
            return True

        while history and history[-1] - ctime >= 60:
            history.pop()

        if len(history) < 3:
            history.insert(0, ctime)
            return True
  • 2.将 MyThrottling 进行配置

    • 1)在 具体View视图类中,添加类属性,仅在该视图类中有效
    class OrderView(APIView):
    
        throttle_classes = [MyThrottling, ]
    
        def post(self, request, *args, **kwargs):
            pass
    
    • 2)在settings.py中进行全局配置,所有资源都有效
    # settings.py
    
    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_CLASSES': ['api.utils.throttl.MyThrottling', ]
    }
    

二、使用rest_framework 提供的SimpleRateThrottle

  • 1.继承 SimpleRateThrottle,并重写get_cache_key(self, request, view)scope 属性
from rest_framework import throttling

class IPThrottling(throttling.SimpleRateThrottle):
    scope = 'IP_rate'

    def get_cache_key(self, request, view):
        return 'cache_' + self.get_ident()
  • 2.在settings.py文件中进行配置,设置访问频率(可以设置多个,根据scope进行匹配)
# settings.py

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'IP_rate': '3/m'
    }
}

注意点:

    1. 控制用户的访问频率需要先确认用户身份SimpleRateThrottle中通过get_cache_key返回用户标示,在上述我们返回'cache_' + self.get_ident().
      get_ident()返回的是用户IP,所以SimpleRateThrottle是基于ip进行限制的。
    1. 我们可以设置多个频率控制,对不同的资源,采用不同的频率[通过scope进行指定]。设置频率的格式为3/m 就是每一分钟允许3次。m就是代表60秒.
      除了m,还可以采用以下:
{'s': 1, 'm': 60, 'h': 3600, 'd': 86400}

三、对SimpleRateThrottle进行定制化

SimpleRateThrottle是基于ip进行验证,我们可以继承SimpleRateThrottle重写get_cache_key方法。

rest_framework提供的UserRateThrottle就是基于django的用户系统以及ip进行频率控制的。

class UserRateThrottle(SimpleRateThrottle):
    """
    Limits the rate of API calls that may be made by a given user.

    The user id will be used as a unique cache key if the user is
    authenticated.  For anonymous requests, the IP address of the request will
    be used.
    """
    scope = 'user'

    def get_cache_key(self, request, view):
        if request.user.is_authenticated:
            # 返回用户标示
            ident = request.user.pk
        else:
            # 返回`ip`标示
            ident = self.get_ident(request)

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

相关文章

  • rest_framework 访问频率控制

    一、访问频率控制的使用 1.创建自己的频率控制类,继承BaseThrottle 2.将 MyThrottling ...

  • Redis 实战 - 控制访问频率

    场景举例 我们日常上网冲浪的时候,常常会遇到这样的情景: 多次输错登陆密码,再次尝试登录,页面提示需要输入正确的图...

  • rest_framework之频率控制与解析器

    1. 频率组件 a. 自定义一个频率类,自定义频率规则 思路分析:(每分钟只能访问三次为例) 代码实现 b. 内...

  • 通过 lua 进行 nginx redis 访问控制

    Nginx来处理访问控制的方法有多种,实现的效果也有多种,访问IP段,访问内容限制,访问频率限制等。 1. 需求分...

  • Django--自定义中间件

    中间件 控制请求流程,限制用户的访问,控制访问频率请求来的时候 自上而下请求走的时候 自下而上 所有中间件中实现的...

  • 获取Web用户真实的访问IP

    在很多 Web 应用场景下,我们会基于 IP 做访问控制或者访问频率限制,又或者根据 IP 获取访问用户的所在地。...

  • Rest-Framework之频率组件

    用频率组件是为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次 自定义频率类,自定义频率规则 自定...

  • Rest-Framework之频率组件

    用频率组件是为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次 自定义频率类,自定义频率规则 自定...

  • Nginx防盗链、Nginx访问控制、Nginx解析php相关配

    image.png Nginx访问控制 Nginx访问控制Nginx访问控制 目录访问控制 正则匹配文件访问控制 ...

  • DRF-访问频率配置(节流)

    访问频率控制(节流) 我们可以先编写一个类 postman校验 获取用户ip 添加访问记录 两种情况,之前说的是第...

网友评论

      本文标题:rest_framework 访问频率控制

      本文链接:https://www.haomeiwen.com/subject/jajmlhtx.html