5.短信验证码接口.md
后台
urls.py
path('sms/', views.SMSViewSet.as_view({'get': 'send'})),
throttles.py
from rest_framework.throttling import SimpleRateThrottle
from django.core.cache import cache
from django.conf import settings
# 结合手机验证码接口来书写
class SMSRateThrottle(SimpleRateThrottle):
scope = 'sms'
def get_cache_key(self, request, view):
# 手机号是通过get请求提交的
mobile = request.query_params.get('mobile', None)
if not mobile:
return None # 不限制
# 手机验证码发送失败,不限制,只有发送成功才限制,如果需求是发送失败也做频率限制,就注释下方三行
code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})
if not code:
return None
return self.cache_format % {
'scope': self.scope,
'ident': mobile,
}
const.py
# 短信验证码缓存key
SMS_CACHE_KEY = 'sms_cache_%(mobile)s'
# 短信验证码缓存时间s
SMS_CACHE_TIME = 300
dev.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
'DEFAULT_THROTTLE_RATES': {
'sms': '1/min'
}
}
views.py
from libs import tx_sms
from django.core.cache import cache
from django.conf import settings
from .throttles import SMSRateThrottle
class SMSViewSet(ViewSet):
# 设置频率限制,一个手机号一分钟只能访问一次
throttle_classes = [SMSRateThrottle]
def send(self, request, *args, **kwargs):
# return APIResponse(result=False)
# 1)接收前台手机号验证手机格式
mobile = request.query_params.get('mobile', None)
if not mobile:
return APIResponse(1, 'mobile field required')
if not re.match(r'^1[3-9][0-9]{9}$', mobile):
return APIResponse(1, 'mobile field error')
# 2)后台产生短信验证码
code = tx_sms.get_code()
# 3)把验证码交给第三方,发送短信
result = tx_sms.send_code(mobile, code, settings.SMS_CACHE_TIME // 60)
# 4)如果短信发送成功,服务器缓存验证码(内存数据库),方便下一次校验
if result:
cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, code, settings.SMS_CACHE_TIME)
# 5)响应前台短信是否发生成功
return APIResponse(result=result)
作者:liuqingzheng
出处:https://www.cnblogs.com/liuqingzheng/articles/17146228.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现