一 短信认证
https://cloud.tencent.com/document/product/382/11672
1.下载模块
pip install qcloudsms_py
2.面条版
# 短信应用 SDK AppID appid = 1400279725 # SDK AppID 以1400开头 # 短信应用 SDK AppKey appkey = "f1a377c327812cdd242ccb66a2fe895b" # 需要发送短信的手机号码 phone_numbers = ["18539419683"] # 短信模板ID,需要在短信控制台中申请 template_id = 457273 # NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请 # 签名 sms_sign = "sages" # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请 # 随机验证码 import random def get_code(): code = '' for i in range(4): code += str(random.randint(0,9)) return code from qcloudsms_py import SmsSingleSender from utils.logging import logger if __name__ == '__main__': ssender = SmsSingleSender(appid, appkey) # 验证码,和过期时间 短信模板中占位符 code = get_code() print(code) params = [code,5] # 当模板没有参数时,`params = []` try: result = ssender.send_with_param(86, phone_numbers[0], template_id, params, sign=sms_sign, extend="", ext="") if result and result['result'] == 0: print('发送成功') except Exception as e: print(e) logger.warning(e) print('发送短信失败')
3.封装版
libs/txsms/settings.py
# 短信应用 SDK AppID - SDK AppID 以1400开头 APP_ID = ... # 短信应用 SDK AppKey APP_KEY = "..." # 短信模板ID,需要在短信控制台中申请 TEMPLATE_ID = ... # 签名 - 是`签名内容`,而不是`签名ID` SMS_SIGN= "..." # 电话前缀 MOBILE_PREFIX = 86
libs/txsms/sms.py
# 通过MacOS ssl安全认证 import ssl ssl._create_default_https_context = ssl._create_unverified_context # 获取验证码的功能 import random def get_code(): code = '' for i in range(4): code += str(random.randint(0, 9)) return code # 短信发送者 from qcloudsms_py import SmsSingleSender from .settings import * sender = SmsSingleSender(APP_ID, APP_KEY) # 发送验证码 from utils.logging import logger
# 号码 验证码 超时时间 def send_sms(mobile, code, exp): try: # 发送短信 response = sender.send_with_param(MOBILE_PREFIX, mobile, TEMPLATE_ID, (code, exp), sign=SMS_SIGN, extend="", ext="") # 成功 if response and response['result'] == 0: return True # 失败 logger.warning('%s - %s' % ('短信发送失败', response['result'])) except Exception as e: # 异常 logger.warning('%s - %s' % ('短信发送失败', e)) return False
libs/txsms/__init__.py
# 包对外提供的功能方法 from .sms import get_code, send_sms
测试
from libs import txsms code = txsms.get_code() print(code) print(txsms.send_sms('电话', code, 5))