腾讯云对象存储对接Python实例

API地址:https://cloud.tencent.com/document/api/436/7751


#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 开发ID、账号密码从腾讯控制台获取
APPID = 10000000
SECRETID = XXXXXXXXXXXXXXXXXXXX
SECRETKEY = YYYYYYYYYYYYYYYYYYY

import hmac
import hashlib


def sign(key, signTime, httpString):
    """
    计算签名
    """
    # key : secretkey
    # signTime : [q-key-time] "1417773892;1417853898"
    # httpString : [HttpMethod]\n[HttpURI]\n[HttpParameters]\n[HttpHeaders]\n
    # stringToSign : "sha1\n$signTime\n$sha1edHttpString\n"

    signKey = hmac.new(key, signTime, hashlib.sha1).hexdigest()
    sha1edHttpString = hashlib.sha1(httpString).hexdigest()
    # "sha1\n$signTime\n$sha1edHttpString\n";
    stringToSign = """sha1\n""" + signTime + """\n""" + sha1edHttpString + """\n"""
    signature = hmac.new(signKey, stringToSign, hashlib.sha1).hexdigest()

    # print signTime
    print "signKey: " + signKey
    # print httpString
    print "sha1edHttpString: " + sha1edHttpString
    print "stringToSign: " + stringToSign
    print "signature: " + signature
    return signature


def Authorization(signTime, signature):
    """
    输出Authorization
    """
    a = "q-sign-algorithm=sha1"
    a += "&q-ak=" + SECRETID
    a += "&q-sign-time=" + signTime
    a += "&q-key-time=" + signTime
    a += "&q-header-list=" + "host"
    a += "&q-url-param-list="
    a += "&q-signature=" + signature
    print "Authorization: " + a
    return a


def postbody(signTime, signature):
    """
    post上传,测试数据为字符串:Hello World!
    """

    body = """POST / HTTP/1.1
Host: test-bucket-1256233904.cos.ap-shanghai.myqcloud.com
Content-Length: 12
Content-Type: multipart/form-data; boundary=e07f2a7876ae4755ae18d300807ad879

--e07f2a7876ae4755ae18d300807ad879
name="key"

a/${filename}
--e07f2a7876ae4755ae18d300807ad879
name="Signature"

""" + Authorization(signTime, signature) + """
--e07f2a7876ae4755ae18d300807ad879
name="file"; filename="empty:a"

Hello World!
--e07f2a7876ae4755ae18d300807ad879--"""

    print body


def main():
    """
    """
    # # get 下载一个文件
    # key = SECRETKEY
    # signTime = "1521081340;2521167740"
    # httpString = "get\n/dir/file.txt\n\nhost=test-bucket-1256233904.cos.ap-shanghai.myqcloud.com\n"
    # signature = sign(key, signTime, httpString)
    # Authorization(signTime, signature)

    # put 上传一个文件
    key = SECRETKEY
    signTime = "1521596488;1521597988"
    httpString = "post\n/3fd577e0-1aa6-4619-bfe9-9df93551b5c9/fileID\n\n\n"
    signature = sign(key, signTime, httpString)
    Authorization(signTime, signature)


if __name__ == "__main__":
    main()

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐