代码改变世界

老男孩腾讯云短信补充说明

2023-01-31 15:11  杰啦  阅读(125)  评论(0)    收藏  举报

Django参照老男孩视频设置短信服务时发现报错,具体为

TypeError: __init__() got an unexpected keyword argument 'encoding'

在查阅相关文档时发现是由于我自己安装的python版本过高导致,我自己python版本的3.11,使用qcloudsms_py会有问题,需要安装腾讯云SDK3.0版本,具体操作如下

1.首先在虚拟环境安装SDK

pip3 install tencentcloud-sdk-python

2.修改sms.py文件

# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.sms.v20210111 import sms_client, models

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:
    """
    res = ""
    try:
        cred = credential.Credential(settings.TENCENT_SID, settings.TENCENT_SKEY) # 腾讯云API秘钥SID/SKEY
        client = sms_client.SmsClient(cred, "ap-guangzhou")     # 腾讯云短信地域,可以不配置

        req = models.SendSmsRequest()

        req.SmsSdkAppId = settings.TENCENT_SMS_APP_ID       # 腾讯云短信应用的SDKAppID
        req.SignName = settings.TENCENT_SMS_SIGNNAME        # 腾讯云短信签名管理的签名内容
        req.TemplateId = template_id                        # 腾讯云短信签名管理的正文模板ID
        req.TemplateParamSet = template_param_list          # 腾讯云短信签名管理的正文模板参数值,也即验证码数值
        req.PhoneNumberSet = ["+86" + phone_num]            # 需要发送的短信号码
        resp = client.SendSms(req)
        # 输出json格式的字符串回包
        res = resp.to_json_string(indent=2)
        print(res)
    except TencentCloudSDKException as err:
        print(err)  # -*- coding: utf-8 -*-
    return res

 至此问题解决,可以正常的发送短信到对应的手机上了!