騰訊雲短信接口完成驗證碼功能

如何快速開通騰訊雲短信服務:https://cloud.tencent.com/document/product/382/37745python

使用python進行配置的間接:https://cloud.tencent.com/document/product/382/11672api

我的使用心得(下面的例子是我我的項目中使用的)

封裝成一個包安全

 

 settings.pydom

# 短信應用 SDK AppID
APPID = 1400009099  # SDK AppID 以1400開頭
# 短信應用 SDK AppKey
APPKEY = "9ff91d87c2cd7cd0ea762f141975d1df37481d48700d70ac37470aefc60f9bad"
# 短信模板ID,須要在短信控制檯中申請
TEMPLATE_ID= 7839  # NOTE: 這裏的模板 ID`7839`只是示例,真實的模板 ID 須要在短信控制檯中申請
# 簽名
SMS_SIGN = "騰訊雲"  # NOTE: 簽名參數使用的是`簽名內容`,而不是`簽名ID`。這裏的簽名"騰訊雲"只是示例,真實的簽名須要在短信控制檯中申請

sms.pyspa

from qcloudsms_py import SmsSingleSender
from .settings import *
from luffyapi.utils.logging import logger
import random
#mac系統的ssl安全驗證
import ssl
ssl._create_default_https_context = ssl._create_unverified_context


sender = SmsSingleSender(APPID,APPKEY)
class Send_sms:

    def __init__(self,mobile,exp):
        self.mobile = mobile
        self.code = self.get_code()
        self.exp = exp
    
    #  短信發送模塊
    def send_sms(self):
        try:
            response = sender.send_with_param(86, self.mobile, TEMPLATE_ID, (self.code, self.exp), sign=SMS_SIGN, extend="", ext="")
        except Exception as e:
            logger.error('sms error: %s' % e)
            return False
        if response and response['result'] == 0:
            return True
        logger.error('sms error:%s' % response['errmsg'])
        return False
    
    #  隨機驗證碼生成模塊
    def get_code(self):
        self.code = ''
        for i in range(4):
            self.code += str(random.randint(0, 9))
        return self.code

__init__.pycode

from .sms import Send_sms

提醒:blog

qcloudsms_py模塊別忘記安裝了,指令以下ip

pip install qcloudsms_py
相關文章
相關標籤/搜索