Elimine un solo objeto, varios objetos por nombre, los objetos que coincidan con un prefijo o un directorio completo.
Los objetos eliminados no se pueden recuperar. Proceda con precaución.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Para eliminar un objeto, debe contar con el permiso
oss:DeleteObject. Para obtener más información, consulte Grant a custom policy.
Eliminar un solo archivo
A continuación se muestra el código para eliminar un objeto llamado exampleobject.txt de un bucket denominado 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')
Eliminar varios archivos
Puede eliminar hasta 1,000 objetos a la vez por nombre, por prefijo o por directorio.
También puede configurar reglas de ciclo de vida para eliminar objetos automáticamente. Para obtener más información, consulte Lifecycle rules based on last modification time.
Eliminar varios objetos con nombres específicos
El siguiente código elimina varios objetos por nombre:
# -*- 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))
Eliminar varios objetos con un prefijo de nombre específico o dentro de un directorio determinado
El siguiente código elimina objetos por prefijo o elimina un directorio completo:
Si no se especifica el prefijo o se establece en NULL, se eliminan todos los objetos del bucket. Especifique los prefijos con 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)
Referencias
Código de ejemplo completo para eliminar archivos: Ejemplos en GitHub.
Operación de API para eliminar un solo archivo: DeleteObject.
Operación de API para eliminar varios archivos: DeleteMultipleObjects.