Python2.X

在使用前,您需要安装openssl,zlib-devel,zlib-static。

# -*- coding:UTF-8 -*-
      import requests
      import time
      import random
      import hmac
      import hashlib
      import base64
      import urllib
      import json
      
      class PaCloudClient:
      
          __endpoint = "https://api.ocftcloud.com/api/v1"
          __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 setHeaders(self, headers):
              """
              Set headers of request
              Params: 
                  headers: a dict which contains headers
              """
              self.__headers = headers
      
      
          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()
               paramDict['headers'] = self.__headers
      
              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.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 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).replace("\r\n", "")
      
              print(">> Signature:")
              print("%s" % signature)
              print("------------------------------------------")        
              paramDict['signature'] = signature
              res = requests.get(self.__endpoint, params=paramDict)
              
              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.setHeaders(headers)
          paclient.doAction(params)
      
      if __name__ == '__main__':
          main()
      
以上内容是否解决了您的问题?
请补全提交信息!
联系我们

电话咨询

400-151-8800

邮件咨询

fincloud@ocft.com

在线客服

工单支持

解决云产品相关技术问题