Todos los productos
Search
Centro de documentos

Object Storage Service:Eliminar objetos (OSS SDK para Python 2.0)

Última actualización: Sep 03, 2026

Este tema describe cómo usar OSS SDK para Python 2.0 para eliminar uno o varios objetos.

Notas de uso

  • El código de ejemplo de este tema usa el ID de región China (Hangzhou) cn-hangzhou y un endpoint público de forma predeterminada. Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las asignaciones entre regiones y endpoints de OSS, consulte Regions and endpoints.

  • Para eliminar un objeto, debe contar con el permiso oss:DeleteObject. Para obtener más información, consulte Grant custom permissions to a RAM user.

Definición del método

Eliminar un solo objeto

delete_object(request: DeleteObjectRequest, **kwargs) → DeleteObjectResult

Eliminar varios objetos

delete_multiple_objects(request: DeleteMultipleObjectsRequest, **kwargs) → DeleteMultipleObjectsResult

Parámetros de solicitud

Parámetro

Tipo

Descripción

request

DeleteObjectRequest

Parámetros de la solicitud, como el nombre del objeto. Para obtener más información, consulte DeleteObjectRequest

DeleteMultipleObjectsRequest

Parámetros de la solicitud, como la lista de objetos por eliminar. Para obtener más información, consulte DeleteMultipleObjectsRequest

Valores de retorno

Tipo

Descripción

DeleteObjectResult

Valor de retorno. Para obtener más información, consulte DeleteObjectResult

DeleteMultipleObjectsResult

Valor de retorno. Para obtener más información, consulte DeleteMultipleObjectsResult

  • Para consultar la definición completa del método para eliminar un solo objeto, consulte delete_object.

  • Para consultar la definición completa del método para eliminar varios objetos, consulte delete_multiple_objects.

Código de ejemplo

Eliminar un solo objeto

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="delete object sample")
# 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.', 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')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

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

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

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    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 using the configured information.
    client = oss.Client(cfg)

    # Execute a request to delete an object. Specify the bucket name and object name.
    result = client.delete_object(oss.DeleteObjectRequest(
        bucket=args.bucket,
        key=args.key,
    ))

    # Print the status code, request ID, version ID, and delete marker of the request to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' delete marker: {result.delete_marker},'
    )

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

Eliminar varios objetos especificados

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="delete multiple objects sample")
# 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.', 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')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Note: If you want to delete multiple objects, add the --key2 command-line argument, which specifies the name of the object.
parser.add_argument('--key2', help='The name of the object.', required=True)

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

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

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    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 using the configured information.
    client = oss.Client(cfg)

    # Define the list of objects to delete.
    # Note: If you want to delete multiple objects, expand the objects list in the following format.
    objects = [oss.DeleteObject(key=args.key), oss.DeleteObject(key=args.key2)]

    # Execute a request to delete multiple objects. Specify the bucket name, encoding type, and object list.
    result = client.delete_multiple_objects(oss.DeleteMultipleObjectsRequest(
        bucket=args.bucket,
        encoding_type='url',
        objects=objects,
    ))

    # Print the status code, request ID, and information about the deleted objects to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' key: {result.deleted_objects[0].key},'
          f' version id: {result.deleted_objects[0].version_id},'
          f' delete marker: {result.deleted_objects[0].delete_marker},'
          f' delete marker version id: {result.deleted_objects[0].delete_marker_version_id},'
          f' encoding type: {result.encoding_type},'
    )

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

Referencias

  • Para consultar el código de ejemplo completo para eliminar un solo objeto, consulte delete_object.py.

  • Para consultar el código de ejemplo completo para eliminar varios objetos, consulte delete_multiple_objects.py.