【摘要】 用Python调用华为云API接口实现发短信,当然能给调用发短信接口前提条件是通过企业实名认证,而且有一个通过审核的短信签名,话不多说,showcode
#!/usr/bin/python3
'''
功 能:对华为云常用API接口进行封装
版权信息: 华为技术有限公司,版权所有(C) 2018-2019
作 者:qshujun
修改记录:2018/02/28 v1.0
'''
import os
import time
import json
from HttpRequest import HttpRequests
class HWCloud():
def __init__(self, domain_name, username, password, region_id):
self.domain_name = domain_name
self.username = username
self.password = password
self.region_id = region_id
self.token_file = "token"
self.iam_endpoint = "https://iam.{region_id}.myhuaweicloud.com"
self.iam_token_uri = "/v3/auth/tokens"
self.smn_endpoint = "https://smn.{region_id}.myhuaweicloud.com"
self.sms_publish_uri = "/v2/{project_id}/notifications/sms"
self.headers = {"content-type": "application/json"}
self.project_id = ""
self.proxies = None
self.get_iam_token()
def get_iam_token(self):
'''
以用户名、密码从IAN换取token并加入headers
:return:
'''
# 先尝试从本地文件读取尚在有效期内的token
if os.path.isfile(self.token_file):
try:
f = open(self.token_file)
token_str = f.read()
f.close()
token_info = json.loads(token_str)
if token_info["expires_at"] > time.time():
self.headers["X-Auth-Token"] = token_info["token"]
self.project_id = token_info["project_id"]
return True
except:
pass
iam_token_url = self.iam_endpoint.format(region_id=self.region_id) + self.iam_token_uri
data = {
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"name": self.username,
"password": self.password,
"domain": {
"name": self.domain_name
}
}
}
},
"scope": {
"project": {
"name": self.region_id
}
}
}
}
auth_timestamp = time.time()
req = HttpRequests(iam_token_url, data=json.dumps(data), type="POST", headers = self.headers, proxies=self.proxies)
print(req.get_text())
if req.get_code() == 201 and "X-Subject-Token" in req.get_headers():
self.headers["X-Auth-Token"] = req.get_headers()["X-Subject-Token"]
req_text = json.loads(req.get_text())
self.project_id = req_text["token"]["project"]["id"]
issued_at = req_text["token"]["issued_at"]
expires_at = req_text["token"]["expires_at"]
expires_timestamp = auth_timestamp + time.mktime(time.strptime(expires_at, "%Y-%m-%dT%H:%M:%S.%fZ")) - time.mktime(time.strptime(issued_at, "%Y-%m-%dT%H:%M:%S.%fZ"))
token_info = {
"token": req.get_headers()["X-Subject-Token"],
"project_id": self.project_id,
"expires_at": expires_timestamp
}
f = open(self.token_file,'w')
f.write(json.dumps(token_info))
f.close()
return True
else:
print("Get IAM token failed, http code: % s, % s" % (str(req.get_code()), req.get_text()))
return False
def sendSms(self, sign_id, endpoint, message):
'''
:param sign_id: 短信签名
:param endpoint: 手机号码
:param message: 短信消息
:return:
'''
sms_publish_url = self.smn_endpoint.format(region_id=self.region_id) + self.sms_publish_uri.format(project_id=self.project_id)
data = {
"endpoint": endpoint,
"message": message,
"sign_id": sign_id
}
req = HttpRequests(sms_publish_url, data=json.dumps(data), type="POST", headers=self.headers, proxies=self.proxies)
if req.get_code() == 200:
return True
else:
print("Send SMS failed, http code: % s, % s" % (str(req.get_code()), req.get_text()))
return False
if __name__ == '__main__':
client = HWCloud('domain_name','username','Password','cn-north-1')
client.sendSms('dddabcde*********************66','181xxxxx110','hello')
依赖的外部HttpRequests类
#!/usr/bin/python
# coding: utf-8
import requests
class HttpRequests():
'''
对requests库封装的GET、POST、PUT等方法调用类
'''
def __init__(self, url, data=None, type='GET', cookie=None, headers=None, proxies=None):
self.url = url
self.data = data
self.type = type
self.cookie = cookie
self.headers = headers
self.proxies = proxies
self.send_request()
def send_request(self):
'''
setup a request
'''
if self.url == None or self.url == '':
raise 'The url should not empty!'
if self.type == 'POST':
self.req = requests.post(self.url, data=self.data, headers=self.headers, proxies=self.proxies)
elif self.type == 'GET':
if self.data == None:
self.req = requests.get(self.url, headers=self.headers, proxies=self.proxies)
else:
self.req = requests.get(self.url, params=self.data, headers=self.headers, proxies=self.proxies)
elif self.type == 'PUT':
self.req = requests.put(self.url, data=self.data, headers=self.headers, proxies=self.proxies)
else:
self.req = None
raise 'The http request type NOT support now!'
def get_code(self):
try:
return self.req.status_code
except:
raise 'get code fail'
def get_url(self):
try:
return self.req.url
except:
raise 'get url fail'
def get_text(self):
try:
return self.req.text
except:
raise 'get text fail'
def get_headers(self):
try:
return self.req.headers
except:
raise 'get headers fail'
def get_cookie(self):
headers = self.get_headers()
if 'set-cookie' in headers:
return headers['set-cookie']
else:
return None
用Python调用华为云API接口发短信的更多相关文章
-
#PHP# 华为云 API 方式发送短信
使用给华为云 消息 服务 API 方式发送短信 代码来自华为云,已通过测试 <?php /** * 华为云发送短信示例代码 * 本段代码需要使用自己的配置信息才能正常运行,出配置信息外,不需要改 ...
-
谁说程序员不懂浪漫?用Python每天自动给女朋友免费发短信
前言 之前发过一篇文章,用 Python 制作的给父母天气预报提醒的小工具天气变冷了,给父母制作一个天气提醒小助手,这篇文章我同步到博客上之后,有读者在评论区留言,对于部分微信没有网页版接口,导致无法 ...
-
利用阿里大于接口发短信(Delphi版)
阿里大于是阿里通信旗下产品,融合了三大运营商的通信能力,提供包括短信.语音.流量直充.私密专线.店铺手机号等个性化服务.每条四分五,价钱还算公道,经老农测试,响应速度非常快,基本上是秒到.官方文档提供 ...
-
Python 调用阿里云 API 收集 ECS 数据
#!/usr/bin/env python # coding: utf-8 # author: Wang XiaoQiang ''' 功能介绍: 1.调用阿里云API,收集所有区域 ECS 信息 2. ...
-
PHP控制阿里云短信API接口实现短信群发功能
阿里云短信支持先使用后支付的原则,价格为4分半1条. 通过SDK可以与网站功能的绑定,实现响应的短信发送功能 现已统一合并升级为:消息服务. 消息服务 阿里云消息服务(Message Service, ...
-
ios-王云鹤 调用ios系统功能---------------打电话、发短信、发邮件
--------------------------------------菜鸟总结,欢迎读者雅正------------------------------------------------- 先 ...
-
用那啥 那啥来着Django来发送Email,结合腾讯云,批量发短信给用户!
你们好,我是来ZB的! 这篇博客是用来发送邮件的,用的是Django框架,很好用.遗憾的是我当时用的阿里云,把腾讯QQ的端口给……给屏蔽了,啊啊啊啊,多么痛的领悟呀.后来用的163网易的邮箱.可以了! ...
-
注册登录页面修订-Python使用redis-手机验证接口-发送短信验证
登录页面修订 views.Login.vue <template> <div class="login box"> <img src="@/ ...
-
使用飞信api接口实现短信发送(只能发送好友)
找了很久才找到一个能用的飞信API接口(http://quanapi.sinaapp.com/fetion.php?u=飞信登录手机号&p=飞信登录密码&to=接收飞信的手机号& ...
随机推荐
-
Oracle 11203 + ASM安装 for HP UX
一,安装前准备 1.创建所需组和用户 /usr/sbin/groupadd -g 1000 oinstall/usr/sbin/groupadd -g 1020 asmadmin/usr/sbin/g ...
-
[moka同学笔记]三、Yii2.0课程笔记(魏曦老师教程)关联字段增加搜索
关联字段增加搜索 post表关联adminuser表,通过post.author_id adminuser.id关联,在YII2.0生成搜索,关联字段搜索时,需要输入关联字段author的id才能搜 ...
-
ural 1221
本来就是个很水的题 就是枚举起点长度然后直接判断就行了 但是比赛的时候写了个大bug 还找不出来 自己太水了 #include <cstdio> #include <c ...
-
c++ bitset使用
A bitset is a special container class that is designed to store bits (elements with only two possibl ...
-
spring security 3中的10个典型用法小结
spring security 3比较庞大,但功能很强,下面小结下spring security 3中值得 注意的10个典型用法 1)多个authentication-provide可以同时使用 &l ...
-
install MariaDB 10.2 on Ubuntu 18
Here are the commands to run to install MariaDB 10.2 from the MariaDB repository on your Ubuntu syst ...
-
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: c
//这个是 配置文件放错了地方 org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing ...
-
python 小练习 7
有一楼梯共n级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第n级,共有多少种走法? 这其实是fibonacci数列,记走法为f(n),在n-1和n-2时你都可以直接跨上去.因此 f(n) = ...
-
Linux sendmail
最近在写自动化巡检脚本,想着怎么预警后自动发送邮件报警. 首先下载最新版本mailx-12.4.tar.bz2 # wget http://sourceforge.net/projects/heirl ...
-
MySql重复查询
MYSQL查询重复记录的方法很多,下面就为您介绍几种最常用的MYSQL查询重复记录的方法,希望对您学习MYSQL查询重复记录方面能有所帮助. 1.查找表中多余的重复记录,重复记录是根据单个字段(peo ...