zoukankan      html  css  js  c++  java
  • 频率组件throttle

    频率组件

    throttle

    """
    系统:
    1)AnonRateThrottle:对同一IP游客的限制
    2)UserRateThrottle:对同一IP登录用户的限制
    必须在settings.py中
    'DEFAULT_THROTTLE_RATES': {
        'user': '10/min',  # 登录的用户一分钟可以访问10次
        'anon': '3/min',  # 游客一分钟可以访问3次
    }
    在视图类中:
    class TempAPIView(APIView):
        ...
        throttle_classes = [AnonRateThrottle, UserRateThrottle]
        
        
    
    自定义:基于auth的Group与Permission表
    1)自定义频率类,继承SimpleRateThrottle,重写get_cache_key,明确scope
        SimpleRateThrottle已经帮我们实现了 allow_request、wait
    2)scope与settings.py的DEFAULT_THROTTLE_RATES配合使用
    3)get_cache_key中完成
        拿到限制信息 ident <= request中获取
        没有限制信息 返回None => 不限制
        有限制信息 返回限制信息字符串 => 有限制
    """
    

    自定义频率类:一分钟一个手机号只允许访问一次接口

    from rest_framework.throttling import SimpleRateThrottle
    
    class ThreeMinRateThrottle(SimpleRateThrottle):
        scope = 'sms'
        def get_cache_key(self, request, view):
            # 对手机号频率限制
            ident = request.data.get('mobile')
            if not ident:  # 为发现限制条件,返回None代表不进行频率限制
                return None
            return self.cache_format % {
                'scope': self.scope,
                'ident': ident
            }
    # settings.py
    'DEFAULT_THROTTLE_RATES': {
        'user': '10/min',  # 登录的用户一分钟可以访问10次
        'anon': '3/min',  # 游客一分钟可以访问3次
        'sms': '1/min',
    }
    
  • 相关阅读:
    编程中Visual Studio常用的快捷键
    解决博易博客后台文章管理页面无法显示分页的问题
    iReaper for WP7 顺利完工
    Visual Studio中web应用程序和网站区别
    SQL批处理
    SQL安全性
    实习之路之篇
    python 日志文件
    后端调用python遥感功能的方式
    C#使用系统的“显示桌面”功能(Shell.Application)
  • 原文地址:https://www.cnblogs.com/SkyOceanchen/p/11923011.html
Copyright © 2011-2022 走看看