Azure 存储:Blob:Python:如果有 blob,则获取指示符

Azure Storage: Blob: Python: Get indicator if there are blobs at all

我有一个 Python 应用程序。在此上下文中,我想从 Azure 存储容器中检索与特定前缀匹配的 blob 引用,然后一次性删除所有 blob。我尝试了以下方法:

container_client: ContainerClient = ContainerClient.from_connection_string(conn_str=storage_account_connection_string, container_name=container_name)

blob_list: ItemPaged[BlobProperties] = container_client.list_blobs(name_starts_with=prefix)

container_client.delete_blobs(*blob_list, delete_snapshots="include")

只要有匹配前缀的 blob,这就可以正常工作。但如果不是这种情况,我在尝试执行 delete_blobs:

时会遇到异常

tuple index out of range

我不想使用 try except,也不想先迭代。我想要一个指示器来告诉我是否有斑点,而无需进行额外的调用。

我该怎么做?

谢谢

编辑: 根据@Gaurav 的建议,以下方法有效:

from azure.storage.blob import ContainerClient, BlobProperties
from azure.core.paging import ItemPaged
from typing import List

blob_paged: ItemPaged[BlobProperties] = container_client.list_blobs(name_starts_with=prefix)
blob_list: List[dict] = list(blob_paged)
number_of_blobs: int = len(blob_list)

if number_of_blobs > 0:
    container_client.delete_blobs(*blob_list, delete_snapshots="include")
    log.debug(f"Deleted '{ number_of_blobs }' blobs and snapshots...")   
else:
    log.debug(f"No blobs to be deleted...")

您应该注意的三件事:

delete_blobs method makes use of Blob Batch operation to delete multiple blobs in a single request. According to the documentation, maximum number of items in a batch can be 256 or the maximum payload size is 4MB (Ref: https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#remarks).

我认为您收到此错误是因为您在 delete_blobs 方法中发送了超过 256 个 blob,或者有效负载的大小超过 4MB。

更新

如果 blobs_list 中的项目为零,您也会收到错误消息。您可以使用以下代码查看项目数(参考:Getting number of elements in an iterator in Python):

number_of_blobs = len(list(blobs_list))