软件测试软件测试职业探索

Python学习练手小项目:Python使用腾讯云-短信服务发送

2019-10-09  本文已影响0人  R_zb

1、准备工作



1.注册腾讯云账号
2.在产品列表内找到短信,在短信内添加应用


添加应用

3.获取对应的SDK AppID 和 App Key


获取应用信息

4.配置短信内容

注:腾讯云的短信服务现在好像也不免费了,之前每个月还会赠送100条免费短信额度。
总结:准备工作准备内容:SDK AppID、App Key、应用签名、短信正文模板ID

2、代码实现

# -*- coding: utf-8 -*-

"""
@author: rzb
@software: PyCharm
@file: sms_qcloud.py
@time: 2019/8/21 11:54
"""

from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
import random


# 使用腾讯云发送手机6位随机验证码
class TestQCloudSMS(object):
    def __init__(self, phone_num):
        self.appid = ****  # 准备工作中的SDK AppID,类型:int
        self.appkey = ****   # 准备工作中的App Key,类型:str
        self.phone_num = phone_num
        self.sign = 'rzbbzr公众号'  # 准备工作中的应用签名,类型:str

    def make_code(self):
        """
        :return: code 6位随机数
        """
        code = ''
        for item in range(6):
            code += str(random.randint(0, 9))
        return code

    def send_msg(self):
        ssender = SmsSingleSender(self.appid, self.appkey)
        try:
            # parms参数类型为list
            rzb = ssender.send_with_param(86, self.phone_num, 短信正文模板ID, [self.make_code()],
                                          sign=self.sign, extend='', ext='')
            print(rzb)
        except HTTPError as http:
            print("HTTPError", http)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    phone_num = ['188********', '185********', '176********']
    sendmsg = TestQCloudSMS(random.choices(phone_num)[0])   # 需传入发送短信的手机号,单发
    sendmsg.send_msg()

3、拓展

官方文档中心里面给出了多种API的详细使用,有兴趣的同学可以去看看
腾讯云文档中心:https://cloud.tencent.com/document/product/382/5976

文档中心

4、闲聊

可用于但不限于以下用途

上一篇 下一篇

猜你喜欢

热点阅读