python-3.x Azure Blob存储:使用SAS令牌下载blob

gupuwyp2  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(154)

我正在尝试从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令牌,让下载访问一个特定的文件在我的容器?

41zrol4v

41zrol4v1#

请参考下面的代码片段,它对我有用。

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")

希望对你有帮助。

相关问题