Help Center/ Object Storage Service/ SDK Reference/ Python/ Object-Related APIs (SDK for Python)/ Using CRC64 to Verify File Consistency (SDK for Python)
Updated on 2026-01-06 GMT+08:00

Using CRC64 to Verify File Consistency (SDK for Python)

  • CRC calculation is a compute-intensive process that requires a large number of shift, exclusive OR (XOR), and table lookup operations. Enabling CRC consumes additional time, and the larger the data volume, the more CPU time is required. In C extension mode, calculating CRC for 1 GB of data takes about 4 to 6 seconds.
  • The OBS SDK for Python requires crcmod to calculate CRC checksums, and crcmod depends on the Python.h file in the python-devel package. crcmod supports both the C extension mode and the Python mode. If there is no Python.h file in the system, the OBS SDK for Python can still be installed, but the C extension mode of crcmod will fail to be installed. In this case, when calculating CRC checksums during upload or download, the system will use the pure Python mode, whose performance and efficiency are far lower than those of the C extension mode. Therefore, before installing the OBS SDK for Python, ensure that python-devel has been installed. If it is not installed, disable CRC64 verification.

You can use the following APIs to verify file consistency using CRC64 during uploads:

You can use the following APIs to verify file consistency using CRC64 during downloads:

You can use the following APIs to obtain the CRC64 value of an object:

Sample Code 1: Performing a Text-Based Upload

This example uses CRC64 to verify file consistency during text upload.

 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
from obs import ObsClient
from obs import PutObjectHeader
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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.
# Before running the sample code, ensure that the environment variables AccessKeyID and SecretAccessKey have been configured.
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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Specify the text to be uploaded.
    content = 'Hello OBS'
    # Specify the additional headers for object upload.
    headers = PutObjectHeader()
    # Calculate the CRC64 value of the data to be uploaded and submit the CRC64 value to the server for verification.
    headers.isAttachCrc64 = True
    # Upload the text.
    resp = obsClient.putContent(bucketName, objectKey, content, headers=headers)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Put Content Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
    else:
        print('Put Content Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put Content Failed')
    print(traceback.format_exc())

Sample Code 2: Performing a File-Based Upload

This example uses CRC64 to verify file consistency during single file upload.

 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
48
49
from obs import ObsClient
from obs import PutObjectHeader
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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.
# Before running the sample code, ensure that the environment variables AccessKeyID and SecretAccessKey have been configured.
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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    # Specify the additional headers for object upload.
    headers = PutObjectHeader()
    # (Optional) Specify the MIME type of the object to be uploaded.
    headers.contentType = 'text/plain'
    # Calculate the CRC64 value of the data to be uploaded and submit the CRC64 value to the server for verification.
    headers.isAttachCrc64 = True
    bucketName = "examplebucket"
    # Specify the object name (the name after the file is uploaded).
    objectKey = "objectname"
    # Specify the full path of the file to be uploaded, for example, aa/bb.txt.
    file_path = 'localfile'
    # Specify the custom metadata of the file.
    metadata = {'meta1': 'value1', 'meta2': 'value2'}
    # Upload the file.
    resp = obsClient.putFile(bucketName, objectKey, file_path, metadata, headers)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
        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())

Sample Code 3: Performing an Append Upload

This example uses CRC64 to verify file consistency during append upload.

 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
48
from obs import ObsClient
from obs import AppendObjectContent, AppendObjectHeader
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    headers = AppendObjectHeader()
    # Calculate the CRC64 value of the data to be uploaded and submit the CRC64 value to the server for verification.
    headers.isAttachCrc64 = True
    # Specify the message body for append upload.
    content = AppendObjectContent()
    # Specify the content to be appended.
    content.content = 'Hello OBS'
    # Specify the starting position (byte 0 in this example) the content is appended to.
    content.position = 0
    # If you upload an object for the first time using the append upload, an error will be reported (status code 409) if an ordinary object with the same name already exists.
    bucketName = "examplebucket"
    # Specify the name of the object to append content to.
    objectKey = "objectname"
    # Append content to the object.
    resp = obsClient.appendObject(bucketName, objectKey, content, headers=headers)

    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Append Object Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
        print('nextPosition:', resp.body.nextPosition)
    else:
        print('Append Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Append Object Failed')   
    print(traceback.format_exc())

Sample Code 4: Performing a Resumable Upload

This example uses CRC64 to verify file consistency during resumable upload.

 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
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)

try:
    bucketName = "examplebucket"
    # Specify the object name (the name after the file is uploaded).
    objectKey = "objectname"
    # Specify the path of the file to be uploaded.
    uploadFile = 'localfile'
    # Specify the number of parts that can be concurrently uploaded.
    taskNum = 5
    # Specify the part size, in bytes. 10 MB is used as an example.
    partSize = 10 * 1024 * 1024
    # Enable the resumable upload by setting enableCheckpoint to True.
    enableCheckpoint = True
    # Upload the object using resumable upload.
    resp = obsClient.uploadFile(bucketName, objectKey, uploadFile, partSize, taskNum, enableCheckpoint, encoding_type='url', isAttachCrc64=True)

    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Upload File Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
    else:
        print('Upload File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Upload File Failed')
    print(traceback.format_exc())

Code Example 5: Performing a Multipart Upload

This example uses CRC64 to verify file consistency during multipart upload.

 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding:utf-8 -*-
from obs import ObsClient,CompleteMultipartUploadRequest, CompletePart
import os
import traceback
# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
   #Specify the bucket name.
    bucketName = "examplebucket"
    #Specify the object name.
    objectKey = "objectname"
    # Specify the MIME type of the object.
    contentType = 'text/plain'
    # Initiate a multipart upload.
    resp = obsClient.initiateMultipartUpload(bucketName, objectKey,
                                             contentType=contentType)
    #Obtain the uploadId.
    uploadId = resp.body["uploadId"]
    #Specify the size of the part to upload.
    partSize = 10 * 1024 * 1024
    #Specify the part number.
    partNum = 1
    # Specify whether object indicates the file path. True is used here. The default value is False.
    isFile = True
    #Specify the local object file to upload.
    filepath = r"D:\tmp\file.txt"
    contentLength = os.path.getsize(filepath)
    #Specify the start offset of a part in the source file.
    offset = 0
    etags = {}
    crc64s = {}

    while offset < contentLength:
        partSize = min(partSize, (contentLength - offset));
        # Upload parts.
        resp1 = obsClient.uploadPart(bucketName, objectKey, partNum, uploadId, filepath, isFile, partSize, offset, isAttachCrc64=True)
        etags[partNum] = resp1.body.etag
        crc64s[partNum] = resp1.body.crc64
        offset = offset + partSize
        partNum = partNum + 1

    completes = []
    for i in range(1, partNum):
        completes.append(CompletePart(i, etags[i], crc64s[i], partSize))
    # Assemble parts.
    completeMultipartUploadRequest = CompleteMultipartUploadRequest(parts = completes)
    resp = obsClient.completeMultipartUpload(bucketName, objectKey, uploadId, completeMultipartUploadRequest, isAttachCrc64=True)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Upload Part Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
    else:
        print('Upload Part Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('multPartsUpload Failed')
    print(traceback.format_exc())

Sample Code 6: Performing a File-Based Download

This example uses CRC64 to verify file consistency during file download.

 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
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    # Specify the full path (localfile as an example) to which the file is downloaded. The full path contains the local file name.
    downloadPath = 'localfile'
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Download the file.
    resp = obsClient.getObject(bucketName, objectKey, downloadPath, isAttachCrc64=True)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Object Failed') 
    print(traceback.format_exc())

Sample Code 7: Performing a Resumable Download

This example uses CRC64 to verify file consistency during resumable download.

 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
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Specify the full path to which the object is downloaded. The full path contains the local file name.
    downloadFile = 'localfile'
    # Specify the number of parts that can be concurrently downloaded.
    taskNum = 5
    # Specify the part size.
    partSize = 10 * 1024 * 1024
    # Enable the resumable download by setting enableCheckpoint to True.
    enableCheckpoint = True
    # Download the object using resumable download.
    resp = obsClient.downloadFile(bucketName, objectKey, downloadFile, partSize, taskNum, enableCheckpoint, isAttachCrc64=True)

    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Download File Succeeded')
        print('requestId:', resp.requestId)
        print('crc64:', resp.body.crc64)
    else:
        print('Download File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Download File Failed')
    print(traceback.format_exc())

Sample Code 8: Performing a Binary Download

This example uses CRC64 to verify file consistency during binary download.

 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
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    bucketName = "examplebucket"
    objectKey = "objectname"
    # If loadStreamInMemory is set to True, downloadpath will be invalid. The binary stream of the file will be downloaded to the memory.
    #Download the object in a binary stream.
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, loadStreamInMemory=True, isAttachCrc64=True)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # Obtain the object content.
        print('buffer:', resp.body.buffer)
        print('size:', resp.body.size)
        print('crc64:', resp.body.crc64)
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Object Failed')
    print(traceback.format_exc())

Sample Code 9: Performing a Streaming Download

This example uses CRC64 to verify file consistency during streaming download.

 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
from obs import GetObjectRequest
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    # Specify the additional parameters for object download.
    getObjectRequest = GetObjectRequest()
    # Rewrite the Content-Type header in the response.
    getObjectRequest.content_type = 'text/plain'
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Download the object using streaming.
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, getObjectRequest=getObjectRequest, loadStreamInMemory=False, isAttachCrc64=True)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        print('crc64 in obs:', resp.body.crc64)
        # Read the object content.
        while True:
            chunk = resp.body.response.read(65536)
            if not chunk:
                break
            print(chunk)
        resp.body.response.close()
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Object Failed')  
    print(traceback.format_exc())

Sample Code 10: Performing a Range-Based Download

This example uses CRC64 to verify file consistency during range download.

 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
from obs import GetObjectHeader
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    # Specify the additional headers for object download.
    headers = GetObjectHeader()
    # Specify the range (0-1000 in this example) of the object bytes to be returned.
    # You can specify multiple ranges when obtaining an object. For example, headers.range='0-1000,2000-3000'.
    headers.range = '0-1000'
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Perform the range download. If loadStreamInMemory is set to True, downloadpath will be invalid, and data streams will be downloaded to the memory.
    resp = obsClient.getObject(bucketName, objectKey, loadStreamInMemory=True, headers=headers)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # Obtain the object content.
        print('buffer:', resp.body.buffer)
        print('crc64:', resp.body.crc64)
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except: 
    print('Get Object Failed')
    print(traceback.format_exc())

Sample Code 11: Obtaining Object Metadata

This example obtains the CRC64 value of objectname in bucket examplebucket.

 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
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables (recommended) or import it 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 using environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently 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)
try:
    bucketName = "examplebucket"
    objectKey = "objectname"
    # Obtain object metadata.
    resp = obsClient.getObjectMetadata(bucketName, objectKey)
    # If status code 2xx is returned, the API was called successfully. Otherwise, the call failed.
    if resp.status < 300:
        print('Get Object Metadata Succeeded')
        print('requestId:', resp.requestId)
        print('etag:', resp.body.etag)
        print('crc64:', resp.body.crc64)
        print('lastModified:', resp.body.lastModified)
        print('contentType:', resp.body.contentType)
        print('contentLength:', resp.body.contentLength)
    else:
        print('Get Object Metadata Failed')
        print('requestId:', resp.requestId)
        print('status:', resp.status)
        print('reason:', resp.reason)
except:
    print('Get Object Metadata Failed')
    print(traceback.format_exc())