在Azure Blob中使用分页列出虚拟文件夹

时间:2019-12-02 19:35:55

标签: python list pagination azure-storage-blobs

我想列出容器中的前10个文件夹,或者在范围内说index = 5并计数= 10,那么我应该从第5个文件夹到第15个文件夹列出。

我尝试使用标记器,但仍然无法实现我想要的

    def listFolders(data):
    try:
        folder_list = []
        containerName = ImportSupporter.getContainerName(data)
        generator = block_blob_service.list_blobs(containerName, delimiter="/")
        count = len(generator.items)
        print(count)
        for blob in generator:
            item = {"SiteId": str(blob.name).split("/")[0]}
            folder_list.append(item)
        return folder_list

    except Exception as e:
        print(e)
        response_object = {"status": "fail", "message": "Unable to list Folders"}
        return response_object, 500

1 个答案:

答案 0 :(得分:0)

这是我在容器中进行虚拟文件夹分页的示例代码。

from azure.storage.blob.baseblobservice import BaseBlobService
import itertools

account_name = '<your account name>'
account_key = '<your account key>'
container_name = '<your container name>'

blob_service = BaseBlobService(
    account_name=account_name,
    account_key=account_key
)

def pagination(index=0, count=10, prefix=None):
    blobs = blob_service.list_blobs(container_name, prefix=prefix, delimiter='/')
    blob_names = (blob.name for blob in blobs if blob.name.endswith('/'))
    return index, count, prefix, list(itertools.islice(blob_names, index, index+count))

为了测试上面的代码,我使用下面的代码在容器中创建了双重嵌套的虚拟文件夹。

service.create_container(container_name)

for i in range(100):
    for j in range(100):
        blob_name = "%03d/%03d/%03d" % (i,j,i*100+j)
        service.create_blob_from_text(container_name, blob_name, blob_name)

容器中虚拟文件夹的结构如下。

<root of container>
|- 000/
    |- 000/
    |- 001/
    .
    .
    .
    |- 099/
|- 001/
    |- 000/
    |- 001/
    .
    .
    .
    |- 099/
.
.
.
|- 099/
    |- 000/
    |- 001/
    .
    .
    .
    |- 099/

enter image description here

然后,我尝试运行下面的测试代码并获得结果。

print(pagination())
print(pagination(5, 10))
print(pagination(prefix='000/'))
print(pagination(5, 10, prefix='002/'))

# (0, 10, None, ['000/', '001/', '002/', '003/', '004/', '005/', '006/', '007/', '008/', '009/'])
# (5, 10, None, ['005/', '006/', '007/', '008/', '009/', '010/', '011/', '012/', '013/', '014/'])
# (0, 10, '000/', ['000/000/', '000/001/', '000/002/', '000/003/', '000/004/', '000/005/', '000/006/', '000/007/', '000/008/', '000/009/'])
# (5, 10, '002/', ['002/005/', '002/006/', '002/007/', '002/008/', '002/009/', '002/010/', '002/011/', '002/012/', '002/013/', '002/014/'])