简体   繁体   中英

List azure containers with specific name type using Python

I am trying to list a bunch of azure containers that have a specific name type - they are all called cycling-asset-group-x where x is a number or a letter eg cycling-asset-group-a, cycling-asset-group-1, cycling-asset-group-b, cycling-asset-group-2.

I only want to print the containers with a number in the suffix ie cycling-asset-group-1, cycling-asset-group-2 etc

How can I do this? Here's where I am up to so far:

account_name   = 'name'
account_key    = 'key'

# connect to the storage account 
blob_service   = BaseBlobService(account_name = account_name, account_key = account_key)
prefix_input_container = 'cycling-asset-group-'

# get a list of the containers - I think it's something like this...? 
cycling_containers = blob_service.list_containers("%s%d" % (prefix_input_container,...)) 

for c in cycling_containers:
    contname = c.name
    print(contname)

Just pass your prefix_input_container value to the parameter prefix of the method list_containers of BaseBlobService , as the code below. Please see the API reference BaseBlobService.list_containers .

list_containers(prefix=None, num_results=None, include_metadata=False, marker=None, timeout=None)[source]

Parameters:
prefix (str) – Filters the results to return only containers whose names begin with the specified prefix.

prefix_input_container = 'cycling-asset-group-'

cycling_containers = blob_service.list_containers(prefix=prefix_input_container) 

# Import regex module to filter the results
import re
re_expression = r"%s\d+$" % prefix_input_container
pattern = re.compile(re_expression)

# There are two ways.
# No.1 Create a generator from the generator of cycling_containers 
filtered_cycling_container_names = (c.name for c in cycling_containers if pattern.match(c.name))
for contname in filtered_cycling_container_names:
    print(contname)

# No.2 Create a name list
contnames = [c.name for c in cycling_containers if pattern.match(c.name)]
print(contnames)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM