def sendTemplateSMS(to, datas, tempId): # 初始化REST SDK rest = REST(serverIP, serverPort, softVersion) rest.setAccount(accountSid, accountToken) rest.setAppId(appId) result = rest.sendTemplateSMS(to, datas, tempId) for k, v in result.items(): if k == 'templateSMS': for k, s in v.item(): print('{}:{}'.format(k, s)) else: print('%s:%s' % (k, v))
class CCPSMS(object): def __init__(self, *args, **kwargs): self.rest = REST(serverIP, serverPort, softVersion) self.rest.setAccount(accountSid, accountToken) self.rest.setAppId(appId) # 利用静态方法实现单例模式 @staticmethod def instance(): if not hasattr(CCPSMS, '_instance'): CCPSMS._instance = CCPSMS() return CCPSMS._instance def sendTemplateSMS(self, to, datas, tempId): try: result = self.rest.sendTemplateSMS(to, datas, tempId) print("状态码:", result, type(result)) except Exception as e: print(e) logging.error(e) raise e if result.get('statusCode') == '000000': return True else: print('请求发送失败') return False def generatecode(self, phone): ''' 4位随机短信验证码''' # code = '%04d'%(random.randint(0, 9999)) # 根据手机号来随机产生6位数字作为验证码 code = '' for i in range(4): code += '%s'%random.choice(phone) print("短息验证码:", code) # 保存到redis数据库中 settings.CONN.setex('sms%s' % phone, EXPIRETIME, code) return code