一.开通腾讯云短信
SDK 文档 :https://cloud.tencent.com/document/product/382/11672
1、官网注册实名账号:https://cloud.tencent.com
2、选取短信服务创建短信应用
3、申请签名与短信模板 - 通过微信公众号申请
# 可以作为我们的测试脚本文件 import os
import django
import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffyapi.settings.dev")
django.setup() # 导包
# from django.conf import settings
#
# print(settings) # <Settings "luffyapi.settings.dev"> 当前的开发环境 from utils.loggings import logger logger.critical('测试logger') # 短信验证 参数的配置
# 短信应用 SDK AppID
appid = 1400278004 # SDK AppID 以1400开头
# 短信应用 SDK AppKey
appkey = "2addd431cd782a9afb75e9c85df66028" # 需要发送短信的手机号码
phone_numbers = [""]
# 短信模板ID,需要在短信控制台中申请
template_id = 457157 # NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请
# 签名
sms_sign = "AlieeMye的技术栈" # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请 # 指定id 单发短信
# 随机验证码
from utils.loggings import logger
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
import random
def get_code():
code = ""
for i in range(5):
num = str(random.randint(0,9)) code += num
return code 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="")
print(result)
if result and result['result'] == 0:
print('短信发送成功')
except HTTPError as e:
print(e)
except Exception as e:
print(e)
# 日志记录错误信息 logger.warning(e)
print('短信发送失败')
# 导包
# from libs import txsms
# code = txsms.get_code()
# print(code)
# print(txsms.send_sms('13122358108', code, 5))
二.腾讯云短信二次封装
seetings 的配置
# 短信应用 SDK AppID - SDK AppID 以1400开头
# 短信的settings 的配置 短信应用SDK APPID >>>以1400
App_ID = 1400278004
# 短信应用 APPker
APP_KEY = '2addd431cd782a9afb75e9c85df66028' # 短信模板ID 需要在控制台中申请 模块 TEMPLATE_ID = 457157 # 签名内容 SMS_SING = 'AlieeMye的技术栈'
# 电话前缀
MOBILE_PREFIX = 86
sms 获取验证码
# 通过MacOS ssl安全认证
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# 获取去短息验证功能 短信发送 # 获取验证号功能
import random def get_code():
code = ""
for i in range(6):
num = str(random.randint(0, 9)) code += num
return code # 短信发送者
from qcloudsms_py import SmsSingleSender
from . import setttings
from .setttings import * ssender = SmsSingleSender(setttings.App_ID, setttings.APP_KEY) # 发送验证码
from utils.loggings import logger def send_sms(mobile, code, exp):
try:
response = ssender.send_with_param(MOBILE_PREFIX, mobile, TEMPLATE_ID, (code, exp), sign=SMS_SING, 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
test.py
# 导包
# from libs import txsms
# code = txsms.get_code()
# print(code)
# print(txsms.send_sms('13122358108', code, 5))