Este tópico descreve como excluir um ou mais arquivos (objetos), ou arquivos com um prefixo específico, de um bucket com controle de versão ativado.
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, use 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 mais sobre a configuração de credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este tópico demonstra a criação de 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.
A exclusão de um objeto requer a permissão
oss:DeleteObject. Para obter mais informações, consulte Conceder uma política personalizada.
Comportamentos de exclusão em um bucket com controle de versão ativado
O comportamento de exclusão é o seguinte:
-
Sem versionId especificado (exclusão reversível):
Se você executar uma operação de exclusão sem especificar um versionId, o OSS insere um marcador de exclusão para a versão atual do objeto em vez de excluí-lo. Ao executar uma operação GetObject posteriormente, o OSS detecta o marcador de exclusão e retorna um erro
404 Not Found. A resposta também inclui o cabeçalhox-oss-delete-marker = truee o número da versão do novo marcador de exclusão no cabeçalhox-oss-version-id.Um valor verdadeiro para
x-oss-delete-markerindica que a versão correspondente aox-oss-version-idretornado é um marcador de exclusão. -
Com versionId especificado (exclusão permanente):
Ao executar uma operação de exclusão e especificar um versionId, o OSS exclui permanentemente essa versão do objeto com base no parâmetro
versionIddo objetoparams. Para excluir uma versão com o ID "null", utilize o parâmetroparamse definaparams['versionId'] = "null". O OSS trata a string "null" como o versionId "null" e exclui o objeto com esse versionId.
Excluir um único arquivo
Os exemplos a seguir mostram como excluir permanentemente ou de forma reversível um único objeto.
-
Exclusão permanente
O código a seguir mostra como excluir permanentemente um objeto especificando seu versionId:
# -*- coding: utf-8 -*- import os import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of 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" # Set yourBucketName to the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) # Set yourObjectName to the full path of the object. Do not include the bucket name. Example: example/test.txt. object_name = 'yourObjectName' # Specify the versionId of the object. This can also be the versionId of a delete marker. params = dict() params['versionId'] = 'yourObjectVersionIdOrDeleteMarkerVersionId' # Delete the object or the object associated with the delete marker that has the specified versionId. result = bucket.delete_object(object_name, params=params) print("delete object name: ", object_name) # If the versionId of an object is specified, the returned delete_marker is None and the returned versionId is the versionId of the specified object. # If the versionId of a delete marker is specified, the returned delete_marker is True and the returned versionId is the versionId of the specified delete marker. if result.delete_marker: print("delete del-marker versionid: ",result.versionid) else: print("delete object versionid:", result.versionid) -
Exclusão reversível
O código a seguir mostra como excluir reversivelmente um objeto sem especificar um versionId:
# -*- coding: utf-8 -*- import os import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of 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" # Set yourBucketName to the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) # Set yourObjectName to the full path of the object. Do not include the bucket name. Example: example/test.txt. object_name = 'yourObjectName' # Soft delete the object without specifying a versionId. This operation adds a delete marker to the object. result = bucket.delete_object(object_name) # View the delete marker. print("delete marker: ", result.delete_marker) # View the versionId of the returned delete marker. print("delete marker versionid: ", result.versionid)
Excluir vários arquivos
Os exemplos a seguir mostram como excluir permanentemente ou de forma reversível vários objetos.
-
Exclusão permanente
O código a seguir mostra como excluir permanentemente vários objetos e marcadores de exclusão especificando seus versionIds:
# -*- coding: utf-8 -*- import os import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider from oss2.models import BatchDeleteObjectVersion from oss2.models import BatchDeleteObjectVersionList # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of 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" # Set yourBucketName to the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) version_list = BatchDeleteObjectVersionList() # You can pass the versionId of an object or a delete marker. obj1_versionid = 'yourObject1VersionId' obj1_del_marker_versionid = 'yourObject1DelMarkerVersionId' obj2_versionid = 'yourObject2VersionId' obj2_del_marker_versionid = 'yourObject2DelMarkerVersionId' version_list.append(BatchDeleteObjectVersion(key='yourObject1Name', versionid=obj1_versionid)) version_list.append(BatchDeleteObjectVersion(key='yourObject1Name', versionid=obj1_del_marker_versionid)) version_list.append(BatchDeleteObjectVersion(key='yourObject2Name', versionid=obj2_versionid)) version_list.append(BatchDeleteObjectVersion(key='yourObject2Name', versionid=obj2_del_marker_versionid)) # Batch delete objects or delete markers with specified versionIds. result = bucket.delete_object_versions(version_list) # View the versionIds of the deleted objects or delete markers. for del_version in result.delete_versions: print('del object name:', del_version.key) # Check whether a delete marker was deleted. print('Is del marker:', del_version.delete_marker) # If a delete marker was deleted, print the versionId of the deleted delete marker. Otherwise, print the versionId of the deleted object. if del_version.delete_marker: print('del object del_marker.versionid', del_version.delete_marker_versionid) else: print('del object versionid:', del_version.versionid) -
Exclusão reversível
O código a seguir mostra como excluir reversivelmente vários objetos sem especificar seus versionIds:
# -*- coding: utf-8 -*- import os import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider from oss2.models import BatchDeleteObjectVersion from oss2.models import BatchDeleteObjectVersionList # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of 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" # Set yourBucketName to the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) key_list = ['yourObject1Name', 'yourObject2Name'] # After you perform a delete operation without specifying a versionId, a delete marker is added to the object. result = bucket.batch_delete_objects(key_list) for del_version in result.delete_versions: print('key name:', del_version.key) # Print the returned delete marker. print('Is del marker:', del_version.delete_marker) print('key del_marker.versionid', del_version.delete_marker_versionid)
Excluir arquivos com um prefixo específico
O código a seguir mostra como excluir arquivos com um prefixo específico:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of 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.
# Set yourBucketName to the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
prefix = "yourKeyPrefix"
# List the versionIds of all files with the specified prefix and delete these files.
next_key_marker = None
next_versionid_marker = None
while True:
result = bucket.list_object_versions(prefix=prefix, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
for version_info in result.versions:
bucket.delete_object(version_info.key, params={'versionId': version_info.versionid})
for del_marker_info in result.delete_marker:
bucket.delete_object(del_marker_info.key, params={'versionId': del_marker_info.versionid})
is_truncated = result.is_truncated
if is_truncated:
next_key_marker = result.next_key_marker
next_versionid_marker = result.next_versionid_marker
else:
break
Referências
Para obter mais informações sobre a operação de API para excluir um único arquivo, consulte DeleteObject.
Para obter mais informações sobre a operação de API para excluir vários arquivos, consulte DeleteMultipleObjects.