短信接口的频率限制
需求:
# 短信接口频率限制,设置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', # 一分钟一次
}