Below are working examples using the Python interface (including the signature procedure) to compute UPLOAD/DOWNLOAD jobs to Azure Blob Storage using REST API with Shared Key Authorization.
Pay attention to:
- set the correct strToSign path
- specify the correct Content type (that should match the file format)
- use the exact blobname and Content length
UPLOAD
import requests
import hashlib
import base64
import hmac
import datetime
with open('my-fancy-image.png', 'rb') as file:
data = file.read()
blobname = "my-fancy-image.png"
accountname = "my-accountname"
container = "my-container"
api_version = "2015-02-21"
content_length = str(len(data))
content_type = "image/png"
key = "my-key"
key = base64.b64decode(key)
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
strToSign = f"PUT\n\n\n{content_length}\n\n{content_type}\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:{date}\nx-ms-version:{api_version}\n/{accountname}/{container}/{blobname}"
hashed = hmac.new(key, strToSign.encode('utf-8'), hashlib.sha256)
hashInBase64 = base64.b64encode(hashed.digest()).strip()
auth = f"SharedKey {accountname}:{hashInBase64.decode('utf-8')}"
url = f"https://{accountname}.blob.core.windows.net/{container}/{blobname}"
headers = {
"x-ms-version": api_version,
"x-ms-date": date,
"Content-Type": content_type,
"x-ms-blob-type": "BlockBlob",
"Authorization": auth,
"Content-Length": content_length,
}
response = requests.put(url, headers=headers, data=data)
print(response.status_code, response.reason)
DOWNLOAD
import requests
import hashlib
import base64
import hmac
import datetime
blobname = "my-fancy-image.png"
accountname = "my-accountname"
container = "my-container"
api_version = "2015-02-21"
key = "my-key"
key = base64.b64decode(key)
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
strToSign = f"GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:{date}\nx-ms-version:{api_version}\n/{accountname}/{container}/{blobname}"
hashed = hmac.new(key, strToSign.encode('utf-8'), hashlib.sha256)
hashInBase64 = base64.b64encode(hashed.digest()).strip()
auth = f"SharedKey {accountname}:{hashInBase64.decode('utf-8')}"
url = f"https://{accountname}.blob.core.windows.net/{container}/{blobname}"
headers = {
"x-ms-version": api_version,
"x-ms-date": date,
"Authorization": auth,
}
response = requests.get(url, headers=headers)
print(response.status_code, response.reason)