Todos os produtos
Search
Central de documentação

Object Storage Service:Como verificar se um bucket existe usando o OSS SDK for Python 2.0

Última atualização: Sep 22, 2026

Este tópico descreve como verificar se um bucket existe usando o OSS SDK for Python 2.0.

Observações de uso

  • O código de exemplo deste tópico usa o ID cn-hangzhou, da região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket ocorre pelo endpoint público. Para acessar esses recursos a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis, 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 as credenciais de acesso, consulte Configure access credentials.

  • Para verificar se um bucket existe, você precisa da permissão oss:GetBucketAcl. Para obter mais informações, consulte Grant a custom policy.

Método

is_bucket_exist(bucket: str, request_payer: str | None = None, **kwargs) → bool

Parâmetros de requisição

Parâmetro

Tipo

Descrição

bucket

str

O nome do bucket.

Parâmetros de resposta

Tipo

Descrição

bool

O valor de retorno.

Para obter detalhes sobre o método para verificar se um bucket existe, consulte is_bucket_exist.

Código de exemplo

Veja a seguir o código de exemplo para verificar se um bucket existe:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="Check if a specified OSS bucket exists.")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket to check for existence.', required=True)

# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')

def main():
    """
    The main function which is used to parse command line parameters and determine if the specified bucket exists.
    """

    args = parser.parse_args()  # Parse the command-line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration of the SDK and specify the credential provider and region.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If an endpoint is provided, specify the endpoint in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Determine if the specified bucket exists.
    result = client.is_bucket_exist(bucket=args.bucket)

    # Display the result.
    print(f'Bucket {args.bucket} exists: {result}')

if __name__ == "__main__":
    main()  # The entry point of the script. When the script is directly run, the main function is called. 

Referência

  • Para obter o código de exemplo completo usado para verificar se um bucket existe, acesse is_bucket_exist.py.