概述
OSS的集成上传和下载提供了SDK可以直接使用,但实际使用中一些用户受限环境或者设备限制需要使用api方式来实现上传和下载,本文以PutObject接口为例,提供了python实现的demo。
注:建议优先使用OSS提供SDK,本文提供的只是签名实现上传demo,实际使用中需要结合业务来进行改动代码
详细信息
PutObject实现Demo(测试环境python2.7):
# -*- coding: utf-8 -*-
import base64
import hmac
import sha
import urllib2
from datetime import datetime
accesskey = '您的accesskey';
accesskeysecret = '您的AccesskeySecret'
endpoint='oss-cn-hangzhou.aliyuncs.com'
bucket='您的bucket名称'
#您的上传文件路径
object='mytest/test.png'
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
time = datetime.utcnow().strftime(GMT_FORMAT)
print(time)
signature = hmac.new(accesskeysecret,
"PUT\n\nimage/png\n"+time+"\n"+"/"+bucket+"/"+object,sha)
Signature = base64.b64encode(signature.digest())
print("Signature: %s" % Signature)
opener = urllib2.build_opener(urllib2.HTTPHandler)
with open("/Users/wanghe/Documents/20190717101549.png") as f:
data=f.read()
request = urllib2.Request("http://"+bucket+"."+endpoint+"/"+object, data=data)
request.add_header("Authorization", "OSS "+accesskey+":"+Signature)
request.add_header("Content-Type", "image/png")
request.add_header("Date", time)
request.get_method = lambda:"PUT"
url = opener.open(request)