腾讯云短信

# 教程链接 https://pythonav.com/wiki/detail/10/82/#5.%20django%E8%BF%9E%E6%8E%A5redis

# 安装模块

pip install qcloudsms_py

# sms_py文件

# -*- coding:utf-8 -*-
# 腾讯发生短信模块


import ssl
# ssl._create_default_https_context = ssl._create_unverified_context
from qcloudsms_py import SmsMultiSender, SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from django.conf import settings


def send_sms_single(phone_num, template_id, template_param_list):
    """
    单条发送短信
    :param phone_num: 手机号
    :param template_id: 腾讯云短信模板ID
    :param template_param_list: 短信模板所需参数列表,例如:【验证码:{1},描述:{2}】,则传递参数 [888,666]按顺序去格式化模板
    :return:
    """
    appid = settings.TENCENT_SMS_APPID  # 自己应用ID
    appkey = settings.TENCENT_SMS_APPKEY  # 自己应用Key
    sms_sign = settings.TENCENT_SMS_SIGN  # 签名管理里面的 自己腾讯云创建签名时填写的签名内容(使用公众号的话这个值一般是公众号全称或简称)
    sender = SmsSingleSender(appid, appkey)
    try:
        response = sender.send_with_param(86, phone_num, template_id, template_param_list, sign=sms_sign)
    except HTTPError as e:
        response = {'result': 1000, 'errmsg': "网络异常发送失败"}
    return response
# 使用
class tencent_sms(forms.Form):
    telephone = forms.CharField(label='手机号',
                                validators=[RegexValidator(r'^1[3-9][0-9]{9}$', '手机号格式错误!')]
                                )

    def __init__(self, request, *args, **kwargs):
        super(tencent_sms, self).__init__(*args, **kwargs)
        self.request = request

    def clean_telephone(self):
        # 校验当前模板是否存在
        tpl = self.request.GET.get('tpl')
        tpl_templates = settings.TENCENT_SMS_TEMPLATES.get(tpl)
        telephone = self.cleaned_data.get('telephone')
        # print(telephone)
        if not telephone:
            raise ValidationError('手机号不能为空')
        if not tpl_templates:
            raise ValidationError('模板错误')
        # 校验当前手机号是否存在数据库
        if tpl_templates == 'login':
            exits = models.user_info.objects.filter(telephone=telephone).exists()
            if not exits:
                raise ValidationError('该手机号未注册')
        elif tpl_templates == 'register':
            exits = models.user_info.objects.filter(telephone=telephone).exists()
            if exits:
                raise ValidationError('当前手机号已注册,请登录')
        # 发送验证码
        code = random.randrange(1000, 99999)
        res = sms.send_sms_single(telephone, tpl_templates, [code, ])
        # 发送成功存redis
        if res["result"] != 0:
            raise ValidationError(res['errmsg'])
        conn = get_redis_connection("default")
        conn.set(telephone, code, ex=60 * 60)
        return telephone

 

posted @ 2021-10-17 22:52  mofr  阅读(71)  评论(0)    收藏  举报