zoukankan      html  css  js  c++  java
  • 短信接口的频率限制

    短信接口的频率限制

    需求:

    # 短信接口频率限制,设置1分钟1次
    

    前置知识点:

    # 字符串格式化输出
    basic_info_dic = {'name':'surpass','age':18}
    introduce = 'I am %(name)s, %(age)d years old'
    print(introduce%basic_info_dic)
    

    定制短信接口的频率限制,需要定义一个类继承于SimpleRateThrottle,并重写其的get_cache_key方法

    # SimpleRateThrottle
    class SimpleRateThrottle(BaseThrottle):
        cache_format = 'throttle_%(scope)s_%(ident)s'
        scope = None
        THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
        
         def get_cache_key(self, request, view):
            raise NotImplementedError('.get_cache_key() must be overridden')
    

    SMSThrottling

    from rest_framework.throttling import SimpleRateThrottle
    
    
    class SMSThrottling(SimpleRateThrottle):
        scope = 'sms'
    
        def get_cache_key(self, request, view):
            telephone = request.query_params.get('telephone')
            return self.cache_format % {'scope': self.scope, 'ident': telephone}
    
    # 在配置文件中配置频率
        'DEFAULT_THROTTLE_RATES':{
            'sms':'1/m',  # 一分钟一次
        }
            
    # SendMsgView
    class SendMessageView(ViewSet, CheckPhone):
        throttle_classes = [SMSThrottling, ]
        
        def phone_is_valid(self, telephone):
            if not re.match(r'^1[3-9][0-9]{9}$', telephone):
                return False, '手机号格式不合法'
            return True
    
        @action(methods=['GET'], detail=False)
        def send_msg(self, request, *args, **kwargs):
            telephone = request.query_params.get('telephone')
            ret = self.phone_is_valid(telephone)
            if isinstance(ret, tuple):
                _, msg = ret
                return APIResponse(code=101, msg=msg)
            random_code = get_random_code()
            result = send_message(telephone, random_code)
            if not result:
                return APIResponse(code=101, msg='短信验证失败')
            return APIResponse(msg='短信验证成功')
    

    效果:

    局部设置

    scope = 'scope'
    THROTTLE_RATES = {
        'scope': '1/m',  # 一分钟一次
    }
    
  • 相关阅读:
    QML的默认属性default property
    QtCreator下QML翻译
    QML开发常见错误(原)
    qt下的跨目录多工程编译(转)
    git使用笔记
    osgQt支持触摸屏
    Qt资源整理ING
    Visual assint x(转)
    C#开发重用方法
    UDP问题
  • 原文地址:https://www.cnblogs.com/surpass123/p/13366628.html
Copyright © 2011-2022 走看看