我尝试使用 Python 来限制不同用户可以访问 Azure 存储的哪些部分。
我一直在寻找可以为存储容器中的特定目录生成 SAS token 的代码。我希望在我的目录上生成 SAS token 将使我能够访问它包含的文件/blob。 (就像它在 azure.portal 上的工作方式一样,我可以右键单击我的目录并按“生成 SAS”。 然而我还没有找到任何可以归档这个的Python代码。 我能找到的只有以下三个函数:
generate_account_sas()
generate_container_sas()
generate_blob_sas()
在这里找到:https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob?view=azure-python
我尝试使用“generate_blob_sas()”函数,但使用我的目录名称而不是文件/blob。
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 = 'NAME OF MY DIRECTORY'
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
但是,当我尝试使用此网址时,我收到以下响应:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:31qv254a-201e-0509-3f26-8587fb000000 Time:2021-07-30T09:37:21.1142028Z</Message>
<AuthenticationErrorDetail>Signature did not match. String to sign used was rt 2021-07-30T10:08:37Z /blob/my_account/my_container/my_directory/my_file.png 2020-06-12 b </AuthenticationErrorDetail>
</Error>
还有其他方法可以在目录上生成 SAS token 吗?
最佳答案
根据您的描述,您的存储帐户似乎是Data Lake Gen2
。如果是这种情况,那么您将需要使用不同的 SDK。
您使用的 SDK 适用于 Azure Blob 存储(非 Data Lake Gen2)帐户,其中文件夹是虚拟文件夹,而不是真实文件夹。
您想要使用的 SDK 是 azure-storage-file-datalake
您想要用于在目录上生成 SAS token 的方法将是 generate_file_system_sas
.
关于python - 使用 Python 为 Azure Blob 存储中的目录生成 SAS token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68588894/