Azure blob 存储。使用 SAS 令牌访问容器

Azure-blob-storage. Get access to container with SAS token

我正在尝试访问 blob 存储容器,这是我的代码:

from datetime import datetime
from azure.storage.blob import BlobServiceClient
from azure.storage.blob import generate_container_sas
from azure.storage.blob import ContainerSasPermissions

blob_storage_account = 'account name'
blob_storage_container = 'container name'
blob_storage_key = 'account key'

permission = ContainerSasPermissions(read=True, write=True, delete=True, 
                                 list=True,delete_previous_version=True, tag=True)

token = generate_container_sas(account_name=blob_storage_account,
                        container_name=blob_storage_container,
                        account_key=blob_storage_key,
                        permission=permission,
                        expiry='2050-2-25')

url = f'https://{blob_storage_account}.blob.core.windows.net'
blob_service_client = BlobServiceClient(url, credential=token)

container = blob_service_client.get_container_client(blob_storage_container)
container.list_blobs().next()

但是当我使用 list_blobs().next() 方法时出现这个错误:

azure.core.exceptions.ClientAuthenticationError: Server failed to authenticate the request. Make sure 
the value of Authorization header is formed correctly including the signature.
RequestId:42251c89-501e-0056-5156-0af114000000
Time:2021-02-24T02:41:46.8149241Z
ErrorCode:AuthenticationFailed
Error:None

我读了这个question,他们提到重置或调整时区,但这没有用

expiry='2050-2-25'不正确,需要格式为UTC时间,如“2021-02-24T15:33:13Z”。

顺便说一句,你可以直接用ContainerClient.from_container_url(...)得到container_client。

from datetime import datetime, timedelta
from azure.storage.blob import BlobServiceClient
from azure.storage.blob import generate_container_sas
from azure.storage.blob import ContainerSasPermissions
from azure.storage.blob import ContainerClient

blob_storage_account = ''
blob_storage_container = ''
blob_storage_key = ''

permission = ContainerSasPermissions(read=True, write=True, delete=True, 
                                 list=True,delete_previous_version=True, tag=True)
sas_token = generate_container_sas(
        account_name=blob_storage_account,
        container_name=blob_storage_container,
        account_key=blob_storage_key,
        permission=permission,
        expiry='2021-02-24T15:33:13Z'
    )
print(sas_token)

url = "https://"+blob_storage_account+".blob.core.windows.net/"+blob_storage_container
container_client = ContainerClient.from_container_url(
    container_url=url,
    credential=sas_token
)
container_client.list_blobs().next()