python3短信验证码demo,云通讯SDK----python2.X版本升级适配3.X

最近自己做项目时,遇到做手机短信验证码时,官网给的最新SDK是python2.X的,自己开发项目的python版本是python3.7,没办法只能自己一个一个到报错的地方改。PS:这里吐槽一下工具pycharm,没有java的myeclipse好用,myeclipse基本是只要有这个函数,你".“了,那些七七八八的都会显示出来,pycharm有些是遮遮掩掩的,你不去看API文档,你都不知道有这个...
摘要由CSDN通过智能技术生成

最近自己做项目时,遇到做手机短信验证码时,官网给的最新SDK是python2.X的,自己开发项目的python版本是python3.7,没办法只能自己一个一个到报错的地方改。(自己经常用到的百度智能云api的sdk,我遇到的大部分是python2.x的,学会改动SDK,适配python3的版本是必要的)
PS:这里吐槽一下工具pycharm,没有java的myeclipse好用,myeclipse基本是只要有这个函数,你".“了,那些七七八八的都会显示出来,pycharm有些是遮遮掩掩的,你不去看API文档,你都不知道有这个函数,”."了也没用,都不会显示,要纯手工敲出来

我做手机验证码的SDK下载 官网https://www.yuntongxun.com

  • 第一个文件SendTemplateSMS.py
    三个.py文件放在一个文件夹下,启动一下SendTemplateSMS文件就行,from导包的路径可能报错,可能需要改一下导包的路径。
# coding=utf-8

from CCPRestSDK import REST

# import ConfigParser

# 主帐号
accountSid = '*********************';

# 主帐号Token
accountToken = '*********************';

# 应用Id
appId = '*********************';

# 请求地址,格式如下,不需要写http://
serverIP = 'app.cloopen.com';

# 请求端口
serverPort = '8883';

# REST版本号
softVersion = '2013-12-26';


# 发送模板短信
# @param to 手机号码
# @param datas 内容数据 格式为数组 例如:{'12','34'},如不需替换请填 ''
# @param $tempId 模板Id


class CCP(object):
    '''自己封装的发送短信的辅助类'''
    # 用来保存对象的类属性
    instance = None

    def __new__(cls):
        # 判断CCP类有没有已经创建好的对象
        if cls.instance is None:
            obj = super(CCP, cls).__new__(cls)

            # 初始化REST SDK
            obj.rest = REST(serverIP, serverPort, softVersion)
            obj.rest.setAccount(accountSid, accountToken)
            obj.rest.setAppId(appId)

            cls.instance = obj

        return cls.instance

    def send_Template_sms(self, to, datas, temp_Id):
        # 初始化REST SDK

        result = self.rest.sendTemplateSMS(to, datas, temp_Id)
        for k, v in result.items():

            if k == 'templateSMS':
                for k, s in v.items():
                    print('%s:%s' % (k, s))
            else:
                print('%s:%s' % (k, v))


                # sendTemplateSMS(手机号码,内容数据,模板Id)


if __name__ == "__main__":
    ccp = CCP()                                                                       
    # 1代表模板ID,下载SDK的官网api文档有说明
    ret = ccp.send_Template_sms("填你自己的手机号码", ["填你想发送的验证码", "有效时间"], 1)
    
    print(ret)

# coding=utf-8

from hashlib import md5
import base64
import datetime
# import urllib2
import urllib.request

urllib2 = urllib.request

import json
# from xmltojson import xmltojson
from xmltojson import xmltojson
from xml.dom import minidom
from xml.dom import minidom


class REST:
    AccountSid = ''
    AccountToken = ''
    AppId = ''
    SubAccountSid = ''
    SubAccountToken = ''
    ServerIP = ''
    ServerPort = ''
    SoftVersion = ''
    Iflog = True  # 是否打印日志
    Batch = ''  # 时间戳
    BodyType = 'xml'  # 包体格式,可填值:json 、xml

    # 初始化
    # @param serverIP       必选参数    服务器地址
    # @param serverPort     必选参数    服务器端口
    # @param softVersion    必选参数    REST版本号
    def __init__(self, ServerIP, ServerPort, SoftVersion):

        self.ServerIP = ServerIP;
        self.ServerPort = ServerPort;
        self.SoftVersion = SoftVersion;

    # 设置主帐号
    # @param AccountSid  必选参数    主帐号
    # @param AccountToken  必选参数    主帐号Token

    def setAccount(self, AccountSid, AccountToken):
        self.AccountSid = AccountSid;
        self.AccountToken = AccountToken;


        # 设置子帐号

    #
    # @param SubAccountSid  必选参数    子帐号
    # @param SubAccountToken  必选参数    子帐号Token

    def setSubAccount(self, SubAccountSid, SubAccountToken):
        self.SubAccountSid = SubAccountSid;
        self.SubAccountToken = SubAccountToken;

        # 设置应用ID

    #
    # @param AppId  必选参数    应用ID

    def setAppId(self, AppId):
        self.AppId = AppId;

    def log(self, url, body, data):
        print('这是请求的URL:')
        print(url);
        print('这是请求包体:')
        print(body);
        print('这是响应包体:')
        print(data);
        print('********************************')

    # 创建子账号
    # @param friendlyName   必选参数      子帐号名称
    def CreateSubAccount(self, friendlyName):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch;
        sig = md5.new(signature).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SubAccounts?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch;
        auth = base64.encodestring(src).strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # xml格式
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
            <friendlyName>%s</friendlyName>\
            </SubAccount>\
            ''' % (self.AppId, friendlyName)

        if self.BodyType == 'json':
            # json格式
            body = '''{"friendlyName": "%s", "appId": "%s"}''' % (friendlyName, self.AppId)
        data = ''
        req.add_data(body)
        try:
            res = urllib2.urlopen(req);
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {
   '172001': '网络错误'}

    # 获取子帐号
    # @param startNo  可选参数    开始的序号,默认从0开始
    # @param offset 可选参数     一次查询的最大条数,最小是1条,最大是100条
    def getSubAccounts(self, startNo, offset):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch;
        sig = md5.new(signature).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/GetSubAccounts?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch;
        auth = base64.encodestring(src).strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # xml格式
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
            <startNo>%s</startNo><offset>%s</offset>\
            </SubAccount>\
            ''' % (self.AppId, startNo, offset)

        if self.BodyType == 'json':
            # json格式
            body = '''{"appId": "%s", "startNo": "%s", "offset": "%s"}''' % (self.AppId, startNo, offset)
        data = ''
        req.add_data(body)
        try:
            res = urllib2.urlopen(req);
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {
   '172001': '网络错误'}

    # 子帐号信息查询
    # @param friendlyName 必选参数   子帐号名称

    
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值