Todos los productos
Search
Centro de documentos

Object Storage Service:Eliminación de buckets con OSS SDK Python 2.0

Última actualización: Sep 03, 2026

Este tema describe cómo eliminar un bucket mediante Python SDK 2.0.

Notas de uso

  • El código de ejemplo de este tema utiliza el ID de región cn-hangzhou correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si desea acceder a los recursos del bucket desde otros servicios de Alibaba Cloud en la misma región donde se encuentra el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • Los puntos de acceso del bucket están eliminados. Para obtener más información, consulte Access points.

  • Todos los objetos del bucket están eliminados.

    Importante

    Para eliminar un bucket con control de versiones, asegúrese de eliminar todas las versiones actuales y anteriores de los objetos en el bucket. Para obtener más información, consulte Versioning.

    • Si el bucket contiene pocos objetos, elimínelos manualmente. Para obtener más información, consulte Delete objects.

    • Si su bucket contiene una gran cantidad de objetos, configure reglas de ciclo de vida para eliminarlos. Para obtener más información, consulte 生命周期.

  • Las partes generadas por tareas de carga multiparte o cargas reanudables en el bucket están eliminadas. Para obtener más información, consulte Delete parts.

Permisos

De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios de RAM o roles de RAM bajo una cuenta de Alibaba Cloud no tienen ningún permiso de forma predeterminada. La cuenta de Alibaba Cloud o el administrador de la cuenta deben otorgar permisos de operación mediante RAM policies o Bucket Policy.

API

Acción

Descripción

DeleteBucket

oss:DeleteBucket

Elimina un bucket.

Definición del método

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

Parámetros de solicitud

Parámetro

Tipo

Descripción

request

DeleteBucketRequest

Los parámetros de la solicitud. Para obtener más información, consulte DeleteBucketRequest

Parámetros de respuesta

Tipo

Descripción

DeleteBucketResult

Los parámetros de la respuesta. Para obtener más información, consulte DeleteBucketResult

Para consultar la definición completa del método delete_bucket, consulte delete_bucket.

Código de ejemplo

A continuación se muestra un ejemplo de código para eliminar un 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.
  

Referencia