Upload a file to Object Storage Service (OSS) with a signed header using Python
Updated at:
Overview
The OSS SDK includes integrated functions to sign, upload, and download files. However, you may sometimes need to use the API to upload and download files with signatures. This topic provides a Python example of the PutObject operation.
Note
Use the OSS SDK whenever possible. This topic provides only an example of how to upload a file with a signature. Modify the code as needed for your application.
Details
The following example shows how to use the PutObject operation in Python 2.7.
# -*- coding: utf-8 -*-
import base64
import hmac
import sha
import urllib2
from datetime import datetime
accesskey = 'Your AccessKey ID';
accesskeysecret = 'Your AccessKey Secret'
endpoint='oss-cn-hangzhou.aliyuncs.com'
bucket='Your bucket name'
# The path of the file to upload.
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("/path/to/your/local/file.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)
References
Include a signature in the header
Applies to
-
Object Storage Service (OSS)
Is this page helpful?