Azure Blob存储:使用SAS令牌下载blob

时间:2018-01-07 16:16:37

标签: python azure-storage-blobs

我正在尝试从Blob存储帐户中的容器下载文件。

在我的python脚本中,我首先创建一个sas令牌,然后尝试使用它来下载文件

from datetime import datetime, timedelta
from urllib.request import urlretrieve

from azure.storage.blob import (
    BlockBlobService,
    BlobPermissions
)
accountName ="myaccountName"
accountKey = "myaccountKey"
containerName = "mycontainerName"
blob_name = "test.txt"
local_path = "testlocal.txt"

service = BlockBlobService(account_name=accountName, account_key=accountKey)
permission = BlobPermissions(_str="racwd")
sas = service.generate_blob_shared_access_signature(containerName, 'test.txt', permission, datetime.utcnow() + timedelta(hours=1),)



sas_service = BlockBlobService(
    account_name=accountName,
    sas_token= sas 
)


blob_uri = "https://myaccountName.blob.core.windows.net/" + containerName + "/" + blob_name +"?"+ sas

print (sas)
print(blob_uri)
urlretrieve(blob_uri, local_path)

运行它会产生错误

HTTPError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

有没有人知道我如何创建一个sas令牌,可以下载访问我容器中的一个特定文件?

1 个答案:

答案 0 :(得分:4)

请参阅下面的代码片段,它适用于我。

from datetime import datetime, timedelta

from azure.storage.blob import (
    BlockBlobService,
    ContainerPermissions,
)

accountName = "***"
accountKey = "***"
containerName = "***"

blobService = BlockBlobService(account_name=accountName, account_key=accountKey)
sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1))
print sas_token

blobService = BlockBlobService(account_name=accountName, account_key=None, sas_token=sas_token)
blobService.get_blob_to_path(containerName, "1.png", "E://testLocal.png")

希望它对你有所帮助。