2

我正在尝试使用该azure-storage-blob包即时生成 blob SAS URL。此解决方案仅在您拥有现已弃用的azure-storage软件包时才有效,该软件包无法再安装。

我需要一种方法来模仿BlockBlobService.generate_blob_shared_access_signature生成 blob SAS URL 的行为,如下所示:

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)

如果您有已弃用的软件包,则上述解决方案有效,但我需要一个不需要它的解决方案。

4

2 回答 2

10

看看下面的代码:

from datetime import datetime, timedelta
from azure.storage.blob import BlobClient, generate_blob_sas, BlobSasPermissions

account_name = 'STORAGE_ACCOUNT_NAME'
account_key = 'STORAGE_ACCOUNT_ACCESS_KEY'
container_name = 'CONTAINER_NAME'
blob_name = 'IMAGE_PATH/IMAGE_NAME'

def get_blob_sas(account_name,account_key, container_name, blob_name):
    sas_blob = generate_blob_sas(account_name=account_name, 
                                container_name=container_name,
                                blob_name=blob_name,
                                account_key=account_key,
                                permission=BlobSasPermissions(read=True),
                                expiry=datetime.utcnow() + timedelta(hours=1))
    return sas_blob

blob = get_blob_sas(account_name,account_key, container_name, blob_name)
url = 'https://'+account_name+'.blob.core.windows.net/'+container_name+'/'+blob_name+'?'+blob

查看此文档以获取更多详细信息:链接

于 2020-08-29T01:55:46.997 回答
1

请尝试以下代码:

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

您可以在此处了解有关使用新存储 SDK 生成 SAS 令牌的更多信息:https ://azure-storage.readthedocs.io/ref/azure.storage.blob.sharedaccesssignature.html 。

于 2020-06-22T23:55:06.717 回答