Track the upload progress of an object by passing a callback function to bucket.put_object.
Usage notes
This topic uses the public endpoint of the China (Hangzhou) region. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information, see Regions and endpoints.
Access credentials in this topic are read from environment variables. For more information, see Configure access credentials using OSS SDK for Python 1.0.
This topic creates an OSSClient instance using an OSS endpoint. To create an OSSClient instance using custom domain names or Security Token Service (STS), see Initialization.
Track upload progress
Pass a callback function to the progress_callback parameter of bucket.put_object. OSS invokes the callback repeatedly during the upload, passing the number of bytes uploaded so far and the total object size.
Note:total_bytesisNonewhen the total size cannot be determined — for example, when uploading from a stream. Always check forNonebefore calculating a percentage.
The following sample code shows how to display a progress percentage during upload:
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Read access credentials from environment variables.
# Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this example.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint for the region where your bucket is located.
# Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Set the region ID that corresponds to the endpoint.
# Required when using the V4 signature algorithm.
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
def percentage(consumed_bytes, total_bytes):
"""Print upload progress as a percentage.
:param consumed_bytes: Bytes uploaded so far (cumulative).
:param total_bytes: Total object size in bytes, or None if unknown.
"""
if total_bytes:
rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
print('\r{0}% '.format(rate), end='')
sys.stdout.flush()
bucket.put_object('yourObjectName', 'a' * 1024 * 1024, progress_callback=percentage)References
For the complete sample code, see object_progress.py on GitHub.