使用 python API 列出 Azure BlobStorage 上的文件

Mat*_*ias 0 python azure python-3.x azure-blob-storage azure-sdk-python

此代码尝试列出 Blob 存储中的文件:

#!/usr/bin/env python3

import os

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
from datetime import datetime, timedelta
import azure.cli.core as az

print(f"Azure Blob storage v{__version__} - Python quickstart sample")

account_name = "my_account"
container_name = "my_container"
path_on_datastore = "test/path"

def _create_sas(expire=timedelta(seconds=10)) -> str:
    cli = az.get_default_cli()

    expire_date = datetime.utcnow() + expire
    expiry_string = datetime.strftime(expire_date, "%Y-%m-%dT%H:%M:%SZ")
    cmd = ["storage", "container", "generate-sas", "--name", container_name, "--account-name",
           account_name, "--permissions", "lr", "--expiry", expiry_string, "--auth-mode", "login", "--as-user"]
    if cli.invoke(cmd) != 0:
        raise RuntimeError("Could not receive a SAS token for user {}@{}".format(
            account_name, container_name))

    return cli.result.result


sas = _create_sas()
blob_service_client = BlobServiceClient(
    account_url=f"{account_name}.blob.core.windows.net", container_name=container_name, credential=sas)

container_client = blob_service_client.create_container(container_name)
blob_list = container_client.list_blobs()
for blob in blob_list:
    print("\t" + blob.name)

Run Code Online (Sandbox Code Playgroud)

几周前该代码运行得很好,但随后我们总是收到错误:

azure.core.exceptions.ClientAuthenticationError:服务器无法对请求进行身份验证。确保授权标头的值格式正确,包括签名。

有人知道可能出什么问题吗?

附言。使用版本 12.3.2 的 Azure blob 存储包。

[编辑]

出于安全考虑,我们不允许在这里使用帐户密钥。

Roa*_*ner 7

我不完全确定您的代码有什么问题,但看起来您的 SAS 令牌不是预期的格式。您是否测试过 SAS URL 在浏览器中是否有效?

此外,您的_create_sas函数似乎正在使用 Azure CLI 命令创建 SAS 签名。我认为您不需要这样做,因为该包具有生成 SAS 签名azure-storage-blob等方法。generate_account_sas这将消除很多复杂性,因为您无需担心 SAS 签名格式。

from datetime import datetime, timedelta
from azure.storage.blob import (
    BlobServiceClient,
    generate_account_sas,
    ResourceTypes,
    AccountSasPermissions,
)
from azure.core.exceptions import ResourceExistsError

account_name = "<account name>"
account_url = f"https://{account_name}.blob.core.windows.net"
container_name = "<container name>"

# Create SAS token credential
sas_token = generate_account_sas(
    account_name=account_name,
    account_key="<account key>",
    resource_types=ResourceTypes(container=True),
    permission=AccountSasPermissions(read=True, write=True, list=True),
    expiry=datetime.utcnow() + timedelta(hours=1),
)
Run Code Online (Sandbox Code Playgroud)

这为该 SAS 签名提供了对 Blob 容器的读取、写入和列出权限,到期时间为 1 小时。您可以根据自己的喜好更改此设置。

然后,我们可以使用此 SAS 签名作为凭据创建BlobServiceClient,然后创建容器客户端来列出 blob。

# Create Blob service client to interact with storage account
# Use SAS token as credential
blob_service_client = BlobServiceClient(account_url=account_url, credential=sas_token)

# First try to create container
try:
    container_client = blob_service_client.create_container(name=container_name)

# If container already exists, fetch the client
except ResourceExistsError:
    container_client = blob_service_client.get_container_client(container=container_name)

# List blobs in container
for blob in container_client.list_blobs():
    print(blob.name)
Run Code Online (Sandbox Code Playgroud)

注:以上使用的是 version azure-storage-blob==12.5.0,即最新的包。这并不比您的版本领先太多,因此我可能会更新您的代码以使用最新的功能,正如文档中所提供的那样。


更新

如果出于安全原因您无法使用帐户密钥,则可以创建服务主体并为其赋予Storage Blob Data Contributor存储帐户角色。它被创建为 AAD 应用程序,它将有权访问您的存储帐户。

要进行此设置,您可以使用文档中的本指南。

示例代码

from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
token_credential = DefaultAzureCredential()

blob_service_client = BlobServiceClient(
    account_url="https://<my_account_name>.blob.core.windows.net",
    credential=token_credential
)
Run Code Online (Sandbox Code Playgroud)