Track the progress of an upload or download by attaching a callback function to bucket.get_object_to_file.
Usage notes
The examples in this topic use the public endpoint for the China (Hangzhou) region. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For more information, see Regions and endpoints.
Access credentials in these examples are read from environment variables. For setup instructions, see Configure access credentials.
These examples create an OSSClient instance using an OSS endpoint. To create one using a custom domain name or Security Token Service (STS), see Initialization.
How it works
Pass a callback function to the progress_callback parameter of get_object_to_file. OSS calls the callback repeatedly during the download, passing two arguments each time:
| Parameter | Type | Description |
|---|---|---|
consumed_bytes | int | Bytes downloaded so far |
total_bytes | int or None | Total file size in bytes. None if the server response does not include a Content-Length header |
Always check whethertotal_bytesisNonebefore computing a percentage. WithoutContent-Length, the total size is unavailable.
The same progress_callback mechanism applies to upload operations. A callback function written for uploads can be reused for downloads without modification.
Sample code
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Read credentials from environment variables.
# Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Replace with the endpoint for your bucket's region.
# Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region. Required for V4 signatures.
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
def percentage(consumed_bytes, total_bytes):
# total_bytes is None if Content-Length is absent from the HTTP response header.
if total_bytes:
rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
print('\r{0}% '.format(rate), end='')
sys.stdout.flush()
# progress_callback is optional. Remove it to download without progress tracking.
bucket.get_object_to_file('exampledir/exampleobject.txt', 'localfile.txt', progress_callback=percentage)Replace the following placeholders with your actual values:
| Placeholder | Description |
|---|---|
examplebucket | Name of your bucket |
exampledir/exampleobject.txt | Full path of the object in the bucket |
localfile.txt | Local file path to save the downloaded object |
References
For a complete runnable example, see object_progress.py on GitHub.