用Python调用华为云API接口发短信

举报
qshujun 发表于 2018/03/01 14:24:25 2018/03/01
【摘要】 用Python调用华为云API接口实现发短信,当然能给调用发短信接口前提条件是通过企业实名认证,而且有一个通过审核的短信签名,话不多说,showcode

用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


【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。