腾讯云短信验证码案例
开通腾讯云短信
""" 1、官网注册实名账号:https://cloud.tencent.com 2、选取短信服务创建短信应用 3、申请签名与短信模板 - 通过微信公众号申请 """
腾讯云短信二次封装
libs ├── txsms │ ├── __init__.py │ ├── settings.py └ └── sms.py
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))
案例
# 发送验证码接口 from libs import txsms class SMSAPIView(APIView): def post(self, request, *args, **kwargs): # 再次校验手机号合法性 mobile = request.data.get(‘mobile‘) # 校验手机号是否存在及合法 if not mobile or not re.match(r‘^1[3-9]\d{9}$‘, mobile): return APIResponse(1, ‘手机号不合法‘) # 生成验证码 code = txsms.get_code() # 发送验证码 result = txsms.send_sms(mobile, code, SMS_EXP // 60) if not result: return APIResponse(1, ‘验证码发送失败‘) # 发送成功保存验证码到redis中,方便管理 cache.set(SMS_CACHE_KEY %{‘mobile‘:mobile}, code, SMS_EXP) return APIResponse(0, ‘验证码发送成功‘)
原文地址:https://www.cnblogs.com/waller/p/11761448.html
时间: 2024-10-31 18:10:25