Updated on 2024-06-19 GMT+08:00

Obtaining the Upload Progress (SDK for Python)

This example configures a callback function to obtain the object upload progress.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. Here uses EU-Dublin as an example. Replace it with the one in use.
server = "https://obs.eu-west-101.myhuaweicloud.eu" 

# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)

# Obtain the upload progress.
def callback(transferredAmount, totalAmount, totalSeconds):
    # Obtain the average upload rate (KB/s).
    print(transferredAmount * 1.0 / totalSeconds / 1024)
    # Obtain the upload progress in percentage.
    print(transferredAmount * 100.0 / totalAmount)

try:
    bucketName = "examplebucket"
    # Specify an object name (the name displayed after the file is uploaded to the bucket).
    objectKey = "objectname"
    # Specify the full path of the file or folder to be uploaded, for example, aa/bb.txt or aa/.
    file_path = 'localfile'
    # Perform the file-based upload.
    resp = obsClient.putFile(bucketName, objectKey, file_path, progressCallback=callback)
    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        print('etag:', resp.body.etag)
        print('versionId:', resp.body.versionId)
        print('storageClass:', resp.body.storageClass)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put File Failed')
    print(traceback.format_exc())

You can query the upload progress when uploading an object in streaming, file-based, multipart, appendable, or resumable mode.