Um bucket é um contêiner para objetos armazenados no Object Storage Service (OSS). Todos os objetos no OSS residem em buckets, listados em ordem alfabética. Você pode listar os buckets da conta atual da Alibaba Cloud em todas as regiões que atendam a condições específicas.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
O exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
A permissão
oss:ListBucketsé obrigatória para listar buckets. Para mais detalhes, consulte Conceder uma política personalizada.
Listar todos os buckets de uma conta Alibaba Cloud
O código de exemplo abaixo mostra como listar buckets em todas as regiões da conta atual da Alibaba Cloud:
Não é possível usar este código para listar buckets de uma região específica. Por exemplo, se você definir a região do bucket como China (Hangzhou) no código, o sistema listará os buckets de todas as regiões da conta atual da Alibaba Cloud.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
service = oss2.Service(auth, endpoint, region=region)
# List all buckets in all regions within the current account.
for b in oss2.BucketIterator(service):
print(b.name)
Listar buckets cujos nomes contenham um prefixo específico
O exemplo a seguir ilustra como listar buckets cujos nomes contenham o prefixo example em todas as regiões da conta atual da Alibaba Cloud:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
service = oss2.Service(auth, endpoint, region=region)
# List all buckets whose names contain the example prefix within the current account.
for b in oss2.BucketIterator(service, prefix='example'):
print(b.name)
Listar buckets cujos nomes sejam alfabeticamente posteriores ao bucket especificado por marker
O trecho de código abaixo exemplifica como listar buckets cujos nomes aparecem depois de examplebucket, em ordem alfabética, considerando todas as regiões da conta atual da Alibaba Cloud:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
service = oss2.Service(auth, endpoint, region=region)
# List all buckets whose names are alphabetically after examplebucket under the current account. The bucket named examplebucket is not listed.
for b in oss2.BucketIterator(service, marker='examplebucket'):
print(b.name)
Referências
Para visualizar o código de exemplo completo usado na listagem de buckets, acesse o GitHub.
Para obter mais informações sobre a operação de API de listagem de buckets, consulte ListBuckets (GetService).