Puede configurar una barra de progreso para mostrar el avance de una tarea de carga o descarga.
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 conocer 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 configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Ejemplos
A continuación se muestra un ejemplo de código para utilizar una barra de progreso cuando emplea bucket.get_object_to_file para descargar un objeto:
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
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 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)
# If Content-Length is not in the HTTP response headers, the value of total_bytes is None.
# consumed_bytes specifies the size of data that has been downloaded. Unit: bytes.
# total_bytes specifies the total size of the object that you want to download. Unit: bytes.
def percentage(consumed_bytes, total_bytes):
if total_bytes:
rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
# rate specifies the download progress.
print('\r{0}% '.format(rate), end='')
sys.stdout.flush()
# progress_callback is an optional parameter used to return progress information.
bucket.get_object_to_file('yourObjectName', 'yourLocalFile', progress_callback=percentage)
Referencias
Para consultar el código de ejemplo completo sobre cómo configurar barras de progreso en tareas de descarga de objetos, visite GitHub.