Udi
Udi

Reputation: 30534

Azure SDK for Python: How to limit results in list_blobs()?

How can the number of blobs returned from ContainerClient.list_blobs() method can be limited?

The Azure Blob service RESP API docs mentions a maxresults parameter, but it seems it is not honored by list_blobs(maxresults=123).

Upvotes: 2

Views: 1649

Answers (3)

buffalo
buffalo

Reputation: 36

Please use by_page() on the ItemPaged class

pages = ContainerClient.list_blobs(maxresults=123).by_page()
first_page = next(pages)
items_in_page = list(a_page) #this will give you 123 results on the first page
second_page = next(pages) # it will throw exception if there's no second page
items_in_page = list(a_page) #this will give you 123 results on the second page

Upvotes: 1

Udi
Udi

Reputation: 30534

A combination of itertools.islice and the results_per_page parameter (which translates to the REST maxresults parameter) will do the trick:

import itertools

service: BlobServiceClient = BlobServiceClient.from_connection_string(cstr)
cc = service.get_container_client("foo")

n = 42
for b in itertools.islice(cc.list_blobs(results_per_page=n), n):
    print(b.name)

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57696

There's no way to do this currently with the SDK. The maxresults parameter really means "max results per page"; if you have more blobs than this, list_blobs will make multiple calls to the REST API until the listing is complete.

You could call the API directly and ignore pages after the first, but that would require you to handle the details of authentication, parsing the response, etc.

Upvotes: 0

Related Questions