前言
系列文章目录
[Python]目录
文章目录
使用的短信API平台为:容联云(https://www.yuntongxun.com/)
开发者文档:http://doc.yuntongxun.com/pe/5a531a353b8496dd00dcdfe2
- 使用官方提供的SDK实现短信发送
2.1 安装SDK
pip install ronglian-sms-sdk -i https://pypi.tuna.tsinghua.edu.cn/simple
2.2 使用官方的测试用例进行测试
from ronglian_sms_sdk import SmsSDK
accId = '...'
accToken = '...'
appId = '...'
def send_message():
sdk = SmsSDK(accId, accToken, appId)
tid = '1'
mobile = '...'
datas = ('123456', 5)
resp = sdk.sendMessage(tid, mobile, datas)
print(resp)
if __name__ == '__main__':
send_message()
返回的结果为json类型的字符串。
2.3 参数及其参数的查看
初始化方法
; 调用发送短信方法
短信模板:
默认短信模板的tid为1
至于其他的模板
发送手机号:
如果没有认证,测试环境下需要设置短信能够发送的测试手机号
响应参数
返回的为json类型的字符串
; 3. 单例模式实现短信发送
由于每次要发送短信都需要向实例化一个对象,当发送短信的并发数太大时,会对内存造成较大的压力,所以修改为采用单例模式实现。
from ronglian_sms_sdk import SmsSDK
import json
accId = '...'
accToken = '...'
appId = '...'
class SendSmsVerificationCode:
"""发送短信验证码的单例类"""
def __new__(cls, *args, **kwargs):
"""
发送短信验证码单例类的初始化方法
:return: 返回一个发送短信验证码的对象
"""
if not hasattr(cls, '_instance'):
cls._instance = super(SendSmsVerificationCode, cls).__new__(cls, *args, **kwargs)
cls._instance.sdk = SmsSDK(accId, accToken, appId)
return cls._instance
def send_message(self, mobile, datas, tid='1'):
"""
发送短信的方法
@params mobile 字符串类型 mobile = '手机号1,手机号2'
@params tid tid = '容联云通讯平台创建的模板' 默认模板的编号为1
@params datas 元组类型 第一个参数为验证码 第二个参数为验证码的有效时间(对于短信模板1)
:return: 返回发送短信后的响应参数
"""
resp = self.sdk.sendMessage(tid, mobile, datas)
print(json.loads(resp), type(json.loads(resp)))
return resp
if __name__ == '__main__':
sendSmsVerificationCode1 = SendSmsVerificationCode()
sendSmsVerificationCode2 = SendSmsVerificationCode()
sendSmsVerificationCode3 = SendSmsVerificationCode()
print(sendSmsVerificationCode1)
print(sendSmsVerificationCode2)
print(sendSmsVerificationCode3)
res = sendSmsVerificationCode1.send_message('...', ('123456', 5), '1')
print(res)
Original: https://blog.csdn.net/m0_53022813/article/details/127833471
Author: 萤火虫的小尾巴
Title: [Python]实现短信验证码的发送