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)
     
  • 相关阅读:
    《深入理解计算机系统》学习笔记(一)
    遇到一道经典的java面试题
    遍历 Map 的四种方法
    Sql Server 获取本周周一
    sql server 计算两个时间 相差的 几天几时几分几秒
    sql server 通用修改表数据存储过程
    查询表数据通用存储过程
    CodeSmith生成实体类
    visual studio 启动无法打开IIS express
    获取url查询参数的方法
  • 原文地址:https://www.cnblogs.com/plyc/p/14145359.html
Copyright © 2011-2022 走看看