Un bucket es un contenedor que se utiliza para almacenar objetos en Object Storage Service (OSS). En este tema se describe cómo determinar si un bucket existe.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Las credenciales de acceso se obtienen a partir de variables de entorno. Para conocer el procedimiento de configuración de estas credenciales, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Para determinar si un bucket existe, es obligatorio contar con el permiso
oss:GetBucketAcl. Para obtener más información, consulte Grant a custom policy.
Ejemplo
A continuación se muestra un ejemplo de código para determinar si un 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')
Referencia
Para consultar el código de ejemplo completo que permite determinar si un bucket existe, visite GitHub.