zoukankan      html  css  js  c++  java
  • 阿里云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)
  • 相关阅读:
    学习进度汇总
    session系列(一)--之--session 与cookie
    遇到一个合适的人到底有多难
    Spring Bean学习创建及使用<二>
    Spring Bean学习创建及使用<一>
    转发:Java对象及其引用
    多线程分配线程的实现方案:CountDownLatch类
    java基础知识
    java静态标示符static详解
    淘宝TAE平台定时任务包的部署步骤
  • 原文地址:https://www.cnblogs.com/lvhanzhi/p/15033620.html
Copyright © 2011-2022 走看看