zoukankan      html  css  js  c++  java
  • 发送短信验证码接口

    后台

    urls.py
    1
    path('sms/', views.SMSViewSet.as_view({'get': 'send'})),
    throttles.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    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 mobile
    # return self.cache_format % {
    # 'scope': self.scope,
    # 'ident': mobile,}
     
    const.py
    1
    2
    3
    4
    5
    # 短信验证码缓存key
    SMS_CACHE_KEY = 'sms_cache_%(mobile)s'

    # 短信验证码缓存时间s
    SMS_CACHE_TIME = 300
    dev.py
    1
    2
    3
    4
    5
    6
    REST_FRAMEWORK = {
    # 全局自定义异常
    'EXCEPTION_HANDLER': 'luffyapi.utils.exception.common_exception_handler',
    # 短信接口频率限制
    'DEFAULT_THROTTLE_RATES': {
    'sms': '1/m'
    }
    }
     
    views.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    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):
    # 1)接收前台手机号验证手机格式
    mobile = request.query_params.get('mobile', None)
    if not mobile:
    return APIResponse(status=0, msg='没有输入手机号')
    if not re.match(r'^1[3-9][0-9]{9}$', mobile):
    return APIResponse(status=0, msg='手机号错误')
    # 2)后台产生短信验证码
    code = tx_sms.get_code()

    # 3)把验证码交给第三方,发送短信
    # result = tx_sms.send_code(mobile, code)
    # 4)如果短信发送成功,服务器缓存验证码(内存数据库),方便下一次校验
    if code:
    cache.set(mobile,code,180)
    # 5)响应前台短信是否发生成功
    return APIResponse(status=1,msg=code)
     
  • 相关阅读:
    Spring(五)AOP简述
    Spring(四)Bean注入方试
    Spring(三)Bean继续入门
    Spring(二)Bean入门
    Spring(一)简述(转载)
    浅析Java中的final关键字(转载)
    浅谈Java中的深拷贝和浅拷贝(转载)
    eclipse的使用、优化配置
    类与对象【一】
    Java学习方法
  • 原文地址:https://www.cnblogs.com/plyc/p/14145359.html
Copyright © 2011-2022 走看看