短信验证码的使用

发送短信

短信:https://console.cloud.tencent.com/smsv2

sdk指导文档:https://cloud.tencent.com/document/product/382/11672

配置

# @Author : OceanSkychen # @File : settings.py

# 短信应用 SDK AppID
APP_ID = 1400292581  # SDK AppID 以1400开头
# 短信应用 SDK AppKey
APP_KEY = "**********************************"

# 短信模板ID,需要在短信控制台中申请
TEMPATE_ID = 486086  # NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请
# 签名
SMS_SIGN = "**************"  # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请

调用

# @Author : OceanSkychen # @File : sms.py
import random
from tx_sms import settings
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from utils.loggings import logger

sender = SmsSingleSender(settings.APP_ID, settings.APP_KEY)


# mobile = "18855489882"
# code = 1234
# exp = 10

# params = ["5678"]  # 当模板没有参数时,`params = []`
def send_sms(mobile, code, exp):
    try:
        response = sender.send_with_param(
            86,
            mobile,
            settings.TEMPATE_ID,
            params=(code, exp),
            sign=settings.SMS_SIGN,
            extend="",
            ext="")
        print(response)

        if response and response.get('result') == 0:
            return True
        msg = response.get('result')
    except Exception as msg:
        pass
    logger.error('短信发送失败:%s' % msg)
    return False


# send_sms(mobile=mobile, code=code, exp=exp)


def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))
    return code

# @Author : OceanSkychen # @File : __init__.py.py

from .sms import send_sms, get_code

# 发送短信
# 5754
class SMSAPIView(APIView):
    throttle_classes = [throttles.SMSRateThrottle]

    def post(self, request, *args, **kwargs):
        # 拿到前台手机
        mobile = request.data.get('mobile')
        if not (mobile and re.match(r'^1[3-9][0-9]{9}$', mobile)):
            return APIResponse(2, '手机号格式有误')
        # 获取验证码
        code = tx_sms.get_code()
        # 发送短信
        result = tx_sms.send_sms(mobile, code, settings.SMS_EXP // 60)
        # 服务器缓存验证码
        if not result:
            return APIResponse(1, '发送验证码失败')
        # 进行存储到redis数据库中
        cache.set(settings.SMS_CACHE_KEY % mobile, code, settings.SMS_EXP)
        # 校验发送的验证码与缓存的验证码是否一致
        print('>>>> %s - %s <<<<' % (code, cache.get('sms_%s' % mobile)))
        return APIResponse(0, '发送验证码成功')
原文地址:https://www.cnblogs.com/SkyOceanchen/p/12104030.html