La descarga de un objeto grande puede fallar si la red es inestable o si ocurren otras excepciones. En algunos casos, el error persiste incluso después de varios intentos. Para resolver este problema, Object Storage Service (OSS) ofrece la función de descarga reanudable. Con esta función, OSS divide un objeto en varias partes y descarga cada una por separado. Una vez que se descargan todas las partes, OSS las combina para formar el objeto completo.
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, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Las credenciales de acceso de este tema 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 usar la descarga reanudable, debe contar con el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.
Procedimiento
Para usar la descarga reanudable, siga estos pasos:
Cree un archivo temporal local cuyo nombre esté formado por el nombre original del objeto y un sufijo aleatorio.
Especifique el encabezado Range en la solicitud HTTP para que el objeto se lea según ese rango. Después, el contenido leído se escribe en la posición correspondiente del archivo temporal local.
Cuando finalice la descarga, cambie el nombre del archivo temporal al del archivo de destino. Si el archivo de destino ya existe, los datos descargados sobrescriben su contenido; de lo contrario, se crea un archivo nuevo.
Un fragmento de información de punto de control puede sobrescribir a otro en el disco local, o bien dos nombres de archivos temporales pueden entrar en conflicto. Por lo tanto, no utilice varios programas ni hilos para llamar simultáneamente al método oss2.resumable_download y descargar el mismo objeto hacia un mismo archivo de destino.
Ejemplos
A continuación se muestra un ejemplo de código para ejecutar una descarga reanudable:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
# Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
oss2.resumable_download(bucket, 'exampledir/exampleobject.txt', 'D:\\localpath\\examplefile.txt')
# If you do not specify a directory by using the store parameter, the .py-oss-upload directory is created in the HOME directory to store the checkpoint information.
# You can configure the following optional parameters if you use OSS SDK for Python version 2.1.0 or later.
# import sys
# # If the length of the data to download cannot be determined, the value of total_bytes is None.
# def percentage(consumed_bytes, total_bytes):
# if total_bytes:
# rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
# print('\r{0}% '.format(rate), end='')
# sys.stdout.flush()
# # If you use the store parameter to specify a directory, the checkpoint information is stored in the specified directory. If you use the num_threads parameter to specify the number of concurrent download threads, make sure that the value of oss2.defaults.connection_pool_size is greater than or equal to the number of concurrent download threads. The default number of concurrent threads is 1.
# oss2.resumable_download(bucket, 'exampledir/exampleobject.txt', 'D:\\localpath\\examplefile.txt',
# store=oss2.ResumableDownloadStore(root='/tmp'),
# # Specify that resumable download is used when the length of the object is greater than or equal to the value of the multipart_threshold parameter. The multipart_threshold parameter is optional and its default value is 10 MB.
# multiget_threshold=100*1024,
# # Specify the size of each part. Unit: bytes. The valid part size ranges from 100 KB to 5 GB. The default part size is 100 KB.
# part_size=100*1024,
# # Configure the callback function that you want to use to indicate the progress of the resumable download task.
# progress_callback=percentage,
# # If you use num_threads to set the number of concurrent download threads, set oss2.defaults.connection_pool_size to a value that is greater than or equal to the number of concurrent download threads. The default number of concurrent threads is 1.
# num_threads=4)