Python3.X
<p class="shortdesc"></p>
<pre class="pre codeblock"><code># -*- coding:UTF-8 -*-
import requests
import time
import random
import hmac
import hashlib
import base64
import urllib
import json
class PaCloudClient:
__endpoint = ""
__accessKeyId = ""
__accessKeySecret = ""
__algorithm = "HMAC-SHA256"
__signatureVersion = '1.0'
__version = '2017-01-01'
__headers = {"Accept-Language":"zh-CN,zh"}
def __init__(self, endpoint):
self.__endpoint = endpoint
def __calculate_signature(self, accessKeySecret, dataToSign, signMethod):
"""
calculate signature of raw data with access key secret
"""
digest = hmac.new(accessKeySecret.encode(), dataToSign.encode(), signMethod).digest()
return base64.b64encode(digest)
def __get_signature(self, accessKeySecret, dataToSign):
"""
Sign the data with access key secret
"""
signature = self.__calculate_signature(accessKeySecret, dataToSign, hashlib.sha256)
return signature
def __get_signature_nonce(self):
""""
Return a nonce value for signing data, which is used to guarantee uniqueness for the request
"""
signaturenonce = ''
for i in range(19):
signaturenonce = signaturenonce + str(random.randint(1, 9))
return signaturenonce
def __lower_params(self, paramDict):
"""
Convert all key in param dict to lower case
"""
paramDictNew = {}
for k, v in paramDict.items():
paramDictNew[k.lower()] = v
return paramDictNew
def __add_public_params(self, paramDict):
"""
Put required public paramters to param dict for signing data
"""
paramDict['accessKeyId'] = self.__accessKeyId
paramDict['signatureMethod'] = self.__algorithm
paramDict['signatureVersion'] = self.__signatureVersion
paramDict['version'] = self.__version
paramDict['timestamp'] = self.__get_timestamp_str()
paramDict['signatureNonce'] = self.__get_signature_nonce()
return paramDict
def __build_data_to_sign(self, paramDict):
"""
Build raw data according to certain rules, raw data will be signed before send request
1. Convert all key in param dict to lower case
2. Sort the key in alphabetical order
3. Encode each value in param dict according to url encoding
4. Convert each pair of '{key:value}' in param dict to 'key=value' and link each pair with '&'
for example:
before convert param dict: {"bkey1":"value1", "akey2": "value2", "ckey3": "value3"}
after convert param dict: akey2=value2&bkey1=value1&ckey3=value3
"""
data = ''
lower_params = self.__lower_params(paramDict)
for key in sorted(lower_params.keys()):
paramValue = str(lower_params[key])
encodedParamValue = urllib.parse.quote(paramValue)
encodedParamValueToLower = encodedParamValue.lower()
if data:
data = data + '&' + key.lower() + '=' + encodedParamValueToLower
else:
data = key.lower() + '=' + encodedParamValueToLower
return data
def __get_timestamp_str(self):
"""
Get current timestamp string
"""
return "%d" % (time.time()*1000)
def initAccessKey(self, accessKeyId, accessKeySecret):
"""
Set user's AccessKey
Params:
accessKeyId: Id of access key
accessKeySecret: Secret of access key
"""
self.__accessKeyId = accessKeyId
self.__accessKeySecret = accessKeySecret
def setSignAlgorithm(self, algorithm):
"""
Set algorithm for signature
Params:
algotithm: 'HMAC-SHA1' or 'HMAC-SHA256' is required, default value 'HMAC-SHA256' is recommended
"""
self.__algorithm = algorithm
def setSignatureVersion(self, signatureVersion):
"""
Set signature version of request
Params:
signatureVersion: Default value '1.0'
"""
self.__signatureVersion = signatureVersion
def setVersion(self, version):
"""
Set version of request
Params:
version: Default value '2017-01-01'
"""
self.__version = version
def setHeaders(self, headers):
"""
Set headers of request
Params:
headers: a dict which contain headers
"""
self.__headers = headers
def doAction(self, paramDict):
"""
Request server for a certain api
Params:
paramDict: a dict which contain all required parameter for the certain api
Return:
Response json string
"""
paramDict = self.__add_public_params(paramDict)
dataToSign = self.__build_data_to_sign(paramDict)
print("===========================================================================")
print(">> Param String To Signature:")
print("%s" % dataToSign)
print("------------------------------------------")
signature = self.__get_signature(self.__accessKeySecret, dataToSign)
print(">> Signature:")
print("%s" % signature)
print("------------------------------------------")
paramDict['signature'] = signature
res = requests.get(self.__endpoint, paramDict, headers = self.__headers)
print(">> Request:")
print("%s" % res.url)
print("------------------------------------------")
print(">> Response")
print("%s" % json.dumps(res.json(), indent = 4, ensure_ascii = False))
print("===========================================================================")
return res.json()
def main():
endpoint = 'https://api.ocftcloud.com/api/v1'
accessKeyId = '用户AccessKeyId'
accessKeySecret = '用户AccessKeySecret'
algorithm = "HMAC-SHA256"
signatureVerion = "1.0"
version = "2017-01-01"
params = {
"action": "GetUser"
}
paclient = PaCloudClient(endpoint)
paclient.initAccessKey(accessKeyId, accessKeySecret)
paclient.setSignAlgorithm(algorithm)
paclient.setVersion(version)
paclient.setSignatureVersion(signatureVerion)
paclient.doAction(params)
if __name__ == '__main__':
main()
</code></pre>
提交成功!非常感谢您的反馈,我们会继续努力做到更好!