码迷,mamicode.com
首页 > 编程语言 > 详细

python3.6 通过调用 阿里云 API (非SDK方式) 查询 可用区 例子

时间:2018-09-17 12:30:03      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:hand   ica   start   base64   tin   scribe   art   get请求   Nid   

#!/usr/bin/env python3.5 # -*- coding:utf8 -*- try: import httplib except ImportError: import http.client as httplib import sys, datetime import urllib import urllib.request import urllib.error import urllib.parse import time import json import base64 import hmac, ssl import uuid from hashlib import sha1 # 解决 访问ssl网站证书的问题 try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn‘t verify HTTPS certificates by default pass else: # Handle target environment that doesn‘t support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context class AliyunClient(object): def __init__(self, access_id, access_secret, region,url): self.access_id = access_id self.access_secret = access_secret self.RegionId = region self.url = url # #签名 def sign(self, accessKeySecret, parameters): sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0]) canonicalizedQueryString = ‘‘ for (k, v) in sortedParameters: canonicalizedQueryString += ‘&‘ + self.percent_encode(k) + ‘=‘ + self.percent_encode(v) stringToSign = ‘GET&%2F&‘ + self.percent_encode(canonicalizedQueryString[1:]) # 使用get请求方法 bs = accessKeySecret + ‘&‘ bs = bytes(bs, encoding=‘utf8‘) stringToSign = bytes(stringToSign, encoding=‘utf8‘) h = hmac.new(bs, stringToSign, sha1) # 进行编码 signature = base64.b64encode(h.digest()).strip() return signature def percent_encode(self, encodeStr): encodeStr = str(encodeStr) res = urllib.request.quote(encodeStr) res = res.replace(‘+‘, ‘%20‘) res = res.replace(‘*‘, ‘%2A‘) res = res.replace(‘%7E‘, ‘~‘) return res # 构建除共公参数外的所有URL def make_url(self, params): timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) parameters = { ‘Format‘: ‘JSON‘, ‘Version‘: ‘2014-05-26‘, ‘AccessKeyId‘: self.access_id, ‘SignatureVersion‘: ‘1.0‘, ‘SignatureMethod‘: ‘HMAC-SHA1‘, ‘SignatureNonce‘: str(uuid.uuid1()), ‘TimeStamp‘: timestamp, } for key in params.keys(): parameters[key] = params[key] signature = self.sign(self.access_secret, parameters) parameters[‘Signature‘] = signature url = self.url + "/?" + urllib.parse.urlencode(parameters) return url def do_action(self, params): url = self.make_url(params) request = urllib.request.Request(url) try: conn = urllib.request.urlopen(request) response = conn.read().decode() except urllib.error.HTTPError as e: print(e.read().strip()) raise SystemExit(e) try: res = json.loads(response) except ValueError as e: raise SystemExit(e) return res # 继承原始类 class client(AliyunClient): def __init__(self,access_id,access_secret,region,url): AliyunClient.__init__(self,access_id,access_secret,region,url) def timestrip(self): UTCC = datetime.datetime.utcnow() utcbefore5 = UTCC - datetime.timedelta(minutes=5) Endtime = datetime.datetime.strftime(UTCC, "%Y-%m-%dT%H:%M:%SZ") StartTime = datetime.datetime.strftime(utcbefore5, "%Y-%m-%dT%H:%M:%SZ") return (StartTime, Endtime) def DescribeInstance(self): self.tt = self.timestrip() action_dict = {"Action": "DescribeAvailableResource", "RegionId": self.RegionId, ‘DestinationResource‘: ‘Zone‘} result = self.do_action(action_dict) return result if __name__ == "__main__": a = client(‘xxxxxxxxx‘, ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxx‘,‘cn-beijing‘,‘https://ecs.aliyuncs.com‘) b = a.DescribeInstance() print(b)

结果

{‘RequestId‘: ‘264CD6C2-BA6F-4AC2-B07C-EDEF173E470F‘, ‘AvailableZones‘: {‘AvailableZone‘: [{‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-f‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-c‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-e‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-d‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-a‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-b‘}, {‘Status‘: ‘Available‘, ‘RegionId‘: ‘cn-beijing‘, ‘ZoneId‘: ‘cn-beijing-g‘}]}}

参考:
https://www.cnblogs.com/IPYQ/p/5996868.html

python3.6 通过调用 阿里云 API (非SDK方式) 查询 可用区 例子

标签:hand   ica   start   base64   tin   scribe   art   get请求   Nid   

原文地址:http://blog.51cto.com/hequan/2176032

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!