• 阿里云API签名


    python3阿里云API签名

    import uuid,base64,sys,hashlib,hmac,requests
    from datetime import datetime
    from urllib import parse
    class AliAuth(object):
        Timestamp = datetime.utcnow().isoformat()
        SignatureNonce = str(uuid.uuid1())
        def __init__(self, config, Id=None, key=None):
            assert config['Action'], "Value error"
            self.config = config
            self.url = 'http://ecs.aliyuncs.com/'
            self.id  = ''  #此处填阿里云AK
            self.Key = ''  #此处填阿里云AK
            self.__data = dict({
                "AccessKeyId": self.id,
                "SignatureMethod": 'HMAC-SHA1',
                "SignatureVersion": "1.0",
                "SignatureNonce": self.SignatureNonce,
                "Timestamp": self.Timestamp,
                "Version": "2014-05-26",
                "Format": "JSON"
            }, **self.config)
    
        @classmethod
        def reload(cls, body):
            cls.Timestamp = datetime.utcnow().isoformat()
            cls.SignatureNonce = str(uuid.uuid1())
            return cls(config=body)
    
        @property
        def data(self):
            return self.__data
    
        @data.setter
        def data(self, value):
            if self.__data:
                raise AssertionError("not allow opeartion")
            self.__data = value
    
        @staticmethod
        def percent_encode(encodeStr):
            if isinstance(encodeStr, bytes):
                encodeStr = encodeStr.decode(sys.stdin.encoding)
            res = parse.quote_plus(encodeStr.encode('utf-8'), '')
            res = res.replace('+', '%20').replace('*', '%2A').replace('%7E', '~')
            return res
    
        def auth(self):
            base = sorted(self.data.items(), key=lambda data:data[0])
            canstring = ''
            for k, v in base:
                canstring += '&' + self.percent_encode(k) + '=' + self.percent_encode(v)
            self.Key += "&"
            data = 'POST&%2F&' + self.percent_encode(canstring[1:])
            self._salt(data)
            return self.data
    
        def _salt(self, data):
            result = data.encode(encoding='utf-8')
            uri = hmac.new(self.Key.encode("utf-8"), result, hashlib.sha1).digest()
            key = base64.b64encode(uri).strip()
            self.data['Signature'] = key
            return self.data
    if __name__ == '__main__':
        data={"Action":"DescribeRegions"}
        s = AliAuth(config=data)
        token = s.auth()
        print(token)
        response = requests.post(url="http://ecs.aliyuncs.com/",data=token)
        print(response.text)
  • 相关阅读:
    setHapticFeedbackEnabled在androi的作用
    Android 跑马灯
    jQuery中绑定事件的命名空间详解
    可见即所得的CSS编辑设计
    盘点8种CSS实现垂直居中水平居中的绝对定位居中技术
    用到的知识点
    用PS去除图片中文字的6个方法
    html页面头部里的meta
    px pt em对应关系
    phpMyAdmin安装与配置(涉及LAMP配置)
  • 原文地址:https://www.cnblogs.com/lvhanzhi/p/15033620.html
Copyright © 2020-2023  润新知