03-05 短信验证码接口
码缓存时间s
SMS_CACHE_TIME = 300
utils/throttles.py
from rest_framework.throttling import SimpleRateThrottle
class SMSThrottle(SimpleRateThrottle):
scope = 'sms'
def get_cache_key(self, request, view):
return self.cache_format % {
'scope': self.scope,
'ident': request.query_params.get('telephone')
}
settings/dev.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'sms': '1/m',
},
}
user/views.py
class SMSAPIView(ViewSet):
# 设置频率限制,一个手机号一分钟只能访问一次
throttle_classes = [SMSThrottle, ]
@action(detail=False)
def send(self, request, *args, **kwargs):
"""发送验证码"""
from django.core.cache import cache
from django.conf import settings
from libs.redis.redis_cache import save_redis
from libs.sms import send_sms
from libs.sms import make_code
telephone = request.query_params.get('telephone')
if re.search(r'^1[3-9][0-9]{9}$', telephone):
code = make_code()
is_success = send_sms(code=code, telephone=telephone)
if is_success:
# 方式一: 保存到django提供的缓存中
cache.set(settings.PHONE_CODE_KEY % telephone, code, 60 * 3)
# 方式二: 保存到redis中
# save_redis(code=code, telephone=telephone)
return utils.APIResponse(code=1, msg='验证码发送成功!')
return utils.APIResponse(code=0, msg='验证码发送失败!')
user/urls.py
router = SimpleRouter()
router.register('', views.SMSAPIView, 'sms')
urlpatterns = [
path('', include(router.urls)),
]