Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir buckets com o OSS SDK Python 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como excluir um bucket usando o Python SDK 2.0.

Observações de uso

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre via endpoint público. Para acessar os recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Exclua os pontos de acesso do bucket. Para mais detalhes, consulte Pontos de acesso.

  • Exclua todos os objetos do bucket.

    Importante

    Para excluir um bucket com versionamento ativado, certifique-se de excluir todas as versões atuais e anteriores dos objetos. Consulte Versionamento para obter mais informações.

    • Se o bucket contiver poucos objetos, exclua-os manualmente. Consulte Excluir objetos.

    • Se o bucket contiver muitos objetos, configure regras de ciclo de vida para excluí-los. Consulte Ciclo de vida.

  • Exclua as partes geradas por tarefas de upload multipart ou upload retomável no bucket. Consulte Excluir partes.

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões completas. Usuários RAM ou funções RAM vinculados a essa conta não têm permissões inicialmente. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais necessárias por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

DeleteBucket

oss:DeleteBucket

Exclui um bucket.

Definição do método

delete_bucket(request: DeleteBucketRequest, **kwargs) → DeleteBucketResult

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

request

DeleteBucketRequest

Os parâmetros da solicitação. Para mais informações, consulte DeleteBucketRequest

Parâmetros de resposta

Tipo

Descrição

DeleteBucketResult

Os parâmetros da resposta. Para mais informações, consulte DeleteBucketResult

Para a definição completa do método delete_bucket, consulte delete_bucket.

Código de exemplo

O exemplo a seguir mostra como excluir um bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe that this script is used to delete a specified OSS bucket.
parser = argparse.ArgumentParser(description="Delete a specified OSS bucket.")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket to delete.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is not required.
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 arguments and delete the specified bucket.
    """

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

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

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

    # If the endpoint parameter is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client based on the configurations.
    client = oss.Client(cfg)

    # Construct a request to delete the specified bucket.
    request = oss.DeleteBucketRequest(bucket=args.bucket)
   
    try:
        # Send the request and obtain the response.
        result = client.delete_bucket(request)

        # Print the status code and request ID of the response.
        print(f'status code: {result.status_code},'
              f' request id: {result.request_id}')
    except oss.exceptions.OssError as e:
        # Catch and print possible exceptions.
        print(f"Failed to delete bucket: {e}")

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run.
  

Referência