Um bucket é um contêiner usado para armazenar objetos no Object Storage Service (OSS). Este tópico descreve como determinar se um bucket existe.
Observações
Neste tópico, o endpoint público da região China (Hangzhou) é usado como referência. 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 Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tópico 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 Initialization.
Para determinar se um bucket existe, você precisa ter a permissão
oss:GetBucketAcl. Para obter mais informações, consulte Grant a custom policy.
Exemplo
O código a seguir apresenta um exemplo de como determinar se um bucket específico existe:
# -*- 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"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
def does_bucket_exist(bucket):
try:
bucket.get_bucket_info()
except oss2.exceptions.NoSuchBucket:
return False
except:
raise
return True
# Determine whether the specified bucket exists. If the bucket exists, true is returned. Otherwise, false is returned.
exist = does_bucket_exist(bucket)
if exist:
print('bucket exist')
else:
print('bucket not exist')
Referência
Para acessar o código de exemplo completo usado para determinar se um bucket existe, visite o GitHub.