如何在Python中生成Azure Blob SAS URL? [英] How can I generate an Azure blob SAS URL in Python?
问题描述
我正在尝试使用 azure-storage-blob
包动态生成blob SAS URL.此解决方案仅在您拥有现已弃用的 azure-storage
软件包时有效.已经安装了.
I am trying to generate blob SAS URLs on the fly using the azure-storage-blob
package. This solution only works if you have the now-deprecated azure-storage
package, which cannot be installed anymore.
我需要一种方法来模仿 BlockBlobService.generate_blob_shared_access_signature
的行为以生成Blob SAS URL,如下所示:
I need a way to mimic the behaviour of BlockBlobService.generate_blob_shared_access_signature
to generate a blob SAS URL, like this:
from datetime import datetime, timedelta
from azure.storage.blob import (
BlockBlobService,
ContainerPermissions,
BlobPermissions,
PublicAccess,
)
AZURE_ACC_NAME = '<account_name>'
AZURE_PRIMARY_KEY = '<account_key>'
AZURE_CONTAINER = '<container_name>'
AZURE_BLOB='<blob_name>'
block_blob_service = BlockBlobService(account_name=AZURE_ACC_NAME, account_key=AZURE_PRIMARY_KEY)
sas_url = block_blob_service.generate_blob_shared_access_signature(AZURE_CONTAINER,AZURE_BLOB,permission=BlobPermissions.READ,expiry= datetime.utcnow() + timedelta(hours=1))
print('https://'+AZURE_ACC_NAME+'.blob.core.windows.net/'+AZURE_CONTAINER+'/'+AZURE_BLOB+'?'+sas_url)
如果您已弃用软件包,则上述解决方案有效,但是我需要不需要的解决方案.
The above solution works if you have the deprecated package, but I need a solution which doesn't need it.
推荐答案
请尝试以下代码:
from azure.storage.blob.sharedaccesssignature import BlobSharedAccessSignature
from datetime import datetime, timedelta
AZURE_ACC_NAME = '<account_name>'
AZURE_PRIMARY_KEY = '<account_key>'
AZURE_CONTAINER = '<container_name>'
AZURE_BLOB='<blob_name>'
expiry= datetime.utcnow() + timedelta(hours=1)
blobSharedAccessSignature = BlobSharedAccessSignature(AZURE_ACC_NAME, AZURE_PRIMARY_KEY)
sasToken = blobSharedAccessSignature.generate_blob(AZURE_CONTAINER, AZURE_BLOB, expiry=expiry, permission="r")
print sasToken
您可以在此处了解有关使用新的Storage SDK生成SAS令牌的更多信息:
You can learn more about generating SAS Token using new Storage SDK here: https://azure-storage.readthedocs.io/ref/azure.storage.blob.sharedaccesssignature.html.
这篇关于如何在Python中生成Azure Blob SAS URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!