Cette rubrique explique comment supprimer un ou plusieurs fichiers (objets), ou des fichiers avec un préfixe spécifié, depuis un bucket pour lequel la gestion des versions est activée.
Notes
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.
Les identifiants d'accès utilisés dans cette rubrique proviennent des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès à l'aide du SDK OSS pour Python 1.0.
Cette rubrique montre comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via le Security Token Service (STS), consultez Initialisation.
Pour supprimer un objet, vous devez disposer de l'autorisation
oss:DeleteObject. Pour plus d'informations, consultez Accorder une politique personnalisée.
Comportements de suppression dans un bucket avec gestion des versions activée
Le comportement de suppression varie selon les cas :
-
Sans versionId spécifié (suppression logique) :
Si vous supprimez un objet sans spécifier de versionId, OSS insère un marqueur de suppression pour la version actuelle au lieu de supprimer l'objet. Lors d'une opération GetObject ultérieure, OSS détecte ce marqueur et renvoie une erreur
404 Not Found. La réponse inclut également l'en-têtex-oss-delete-marker = trueainsi que le numéro de version du nouveau marqueur de suppression dans l'en-têtex-oss-version-id.La valeur true de
x-oss-delete-markerindique que la version correspondant aux-oss-version-idrenvoyé est un marqueur de suppression. -
Avec un versionId spécifié (suppression définitive) :
Si vous spécifiez un versionId lors de la suppression, OSS supprime définitivement cette version de l'objet en se basant sur le paramètre
versionIdde l'objetparams. Pour supprimer une version dont l'ID est « null », utilisez le paramètreparamset définissezparams['versionId'] = "null". OSS traite la chaîne « null » comme le versionId « null » et supprime l'objet associé.
Supprimer un seul fichier
Les exemples suivants montrent comment supprimer définitivement ou logiquement un seul objet.
-
Suppression définitive
Le code suivant montre comment supprimer définitivement un objet en spécifiant son 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) -
Suppression logique
Le code suivant montre comment supprimer logiquement un objet sans spécifier de 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)
Supprimer plusieurs fichiers
Les exemples suivants montrent comment supprimer définitivement ou logiquement plusieurs objets.
-
Suppression définitive
Le code suivant montre comment supprimer définitivement plusieurs objets et marqueurs de suppression en spécifiant leurs 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) -
Suppression logique
Le code suivant montre comment supprimer logiquement plusieurs objets sans spécifier leurs 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)
Supprimer des fichiers avec un préfixe spécifié
Le code suivant montre comment supprimer des fichiers ayant un préfixe spécifié :
# -*- 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
Références
Pour plus d'informations sur l'opération API permettant de supprimer un seul fichier, consultez DeleteObject.
Pour plus d'informations sur l'opération API permettant de supprimer plusieurs fichiers, consultez DeleteMultipleObjects.