Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir objetos (OSS SDK for Python 2.0)

Última atualização: Jul 03, 2026

Este tópico descreve como usar o OSS SDK for Python 2.0 para excluir um ou mais objetos.

Observações de uso

  • O código de exemplo deste tópico usa, por padrão, o ID da região China (Hangzhou) cn-hangzhou e um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • A exclusão de um objeto requer a permissão oss:DeleteObject. Para mais detalhes, consulte Conceder permissões personalizadas a um usuário RAM.

Definição do método

Excluir um único objeto

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

Excluir vários objetos

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

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

request

DeleteObjectRequest

Parâmetros da solicitação, como o nome do objeto. Para mais informações, consulte DeleteObjectRequest

DeleteMultipleObjectsRequest

Parâmetros da solicitação, como a lista de objetos a excluir. Para mais informações, consulte DeleteMultipleObjectsRequest

Valores de retorno

Tipo

Descrição

DeleteObjectResult

Valor de retorno. Para mais informações, consulte DeleteObjectResult

DeleteMultipleObjectsResult

Valor de retorno. Para mais informações, consulte DeleteMultipleObjectsResult

  • Para consultar a definição completa do método de exclusão de um único objeto, veja delete_object.

  • Para consultar a definição completa do método de exclusão de vários objetos, veja delete_multiple_objects.

Código de exemplo

Excluir um único 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.

Excluir vários 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.

Referências

  • Para obter o código de exemplo completo de exclusão de um único objeto, consulte delete_object.py.

  • Para obter o código de exemplo completo de exclusão de vários objetos, consulte delete_multiple_objects.py.