Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). 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 regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este exemplo demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
Para excluir um objeto, você precisa da permissão
oss:DeleteObject. Para mais detalhes, consulte Conceder uma política personalizada.
Excluir um único arquivo
O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado examplebucket:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with the bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Delete the file.
# Replace yourObjectName with the full path of the file to delete. The full path does not include the bucket name. For example, exampledir/exampleobject.txt.
# To delete a folder, set yourObjectName to the folder name. Empty the folder before deleting it.
bucket.delete_object('exampledir/exampleobject.txt')
Excluir vários arquivos
Você pode excluir até 1.000 objetos por vez por nome, prefixo ou diretório.
Também é possível configurar regras de ciclo de vida para excluir objetos automaticamente. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação.
Excluir vários objetos com nomes especificados
O código abaixo exclui múltiplos objetos por nome:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with the bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Batch delete three files. You can delete up to 1,000 files in a single request.
# Specify the full paths of the three files to delete. The full paths do not include the bucket name.
result = bucket.batch_delete_objects(['exampleobject1.jpg', 'testobject2.png', 'destobject3.txt'])
# Print the names of the successfully deleted files.
print('\n'.join(result.deleted_keys))
Excluir vários objetos com o prefixo de nome especificado ou no diretório especificado
O exemplo a seguir exclui objetos por prefixo ou remove um diretório completo:
Se o prefixo não for especificado ou for definido como NULL, todos os objetos do bucket serão excluídos. Defina os prefixos com cuidado.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with the bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Set the prefix for deletion. Use 'src' to delete all files with 'src' prefix.
# Use 'src/' to delete only the folder 'src' and all files within it.
# prefix = 'src/'
# Delete multiple files.
for obj in oss2.ObjectIterator(bucket, prefix=prefix):
bucket.delete_object(obj.key)
Referências
Código de exemplo completo para exclusão de arquivos: Exemplos no GitHub.
Operação de API para excluir um único arquivo: DeleteObject.
Operação de API para excluir vários arquivos: DeleteMultipleObjects.