Updated on 2024-04-23 GMT+08:00

Copying a Part (SDK for Python)

Function

This API copies a part to a specified bucket. This request must contain the multipart upload ID.

After creating a multipart upload, you can specify the upload ID and upload parts for the multipart upload. Alternatively, you can call this API to add a part (part of an object or the whole object).

Assume that you copy a source object and save it as part1. If there is already a part1 before the copy, the new part1 will overwrite the existing part1. Then, only the new part1 can be listed and the old part1 is deleted. Therefore, when using this API, ensure that the target part does not exist or is no longer used, to avoid accidental deletion. The source object keeps unchanged in the entire copy process.

Restrictions

  • To copy a part, you must be the bucket owner or have the required permission (obs:object:PutObject in IAM or PutObject in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Configuring an Object Policy.
  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
  • You cannot determine whether a part copy is successful only based on status_code in the HTTP header returned. A 200 response indicates that the server has received the request and starts to process the request. Only when the response body contains ETag, the copy is successful, or the copy fails.

Method

ObsClient.copyPart(bucketName, objectKey, partNumber, uploadId, copySource, copySourceRange, destSseHeader, sourceSseHeader)

Request Parameters

Table 1 List of request parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

str

Yes

Explanation:

Target bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.

Default value:

None

objectKey

str

Yes

Explanation:

Object name. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name.

For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

NOTE:

The object URL is in the following format: https://Bucket name.Domain name/Folder directory level/Object name. If this object is stored in the root directory of the bucket, its URL does not contain the folder directory level.

partNumber

int

Yes

Explanation:

Part number

Value range:

[1,10000]

Default value:

None

uploadId

str

Yes

Explanation:

Multipart upload ID, for example, 000001648453845DBB78F2340DD460D8

Value range:

The value must contain 32 characters.

Default value:

None

copySource

str

Yes

Explanation:

Parameter used to specify the source bucket, source object, and source object version ID which can be left blank. It is in the format of SourceBucketName/SourceObjectName?versionId=SourceObjectVersionId.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.
  • An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name.

    For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

Default value:

None

copySourceRange

str

No

Explanation:

Copy source range. For example, 0-999 indicates the range is from byte 1 to byte 1,000.

Value range:

Value range: 0 to the object length minus 1. Format: x-y, indicating the range is from byte x+1 to byte y+1

Restrictions:

The upper limit of range is the length of the object minus 1. If the specified value exceeds this limit, the length of the object minus 1 is used.

Default value:

None

destSseHeader

SseCHeader or SseKmsHeader

No

Explanation:

Server-side encryption header used for encrypting the target object. For details, see Table 2 or Table 3.

sourceSseHeader

SseCHeader

No

Explanation:

Server-side decryption header used for decrypting the source object. For details, see Table 2.

Table 2 SseCHeader

Parameter

Type

Mandatory (Yes/No)

Description

encryption

str

Yes

Explanation:

SSE-C used for encrypting objects

Value range:

AES256

Default value:

None

key

str

Yes

Explanation:

Key used in SSE-C encryption. It corresponds to the encryption method. For example, if encryption is set to AES256, the key is calculated using the AES-256 algorithm.

Value range:

The value must contain 32 characters.

Default value:

None

Table 3 SseKmsHeader

Parameter

Type

Mandatory (Yes/No)

Description

encryption

str

Yes

Explanation:

SSE-KMS used for encrypting objects

Value range:

kms

Default value:

None

key

str

No

Explanation:

Master key used in SSE-KMS

Value range:

The following two formats are supported:

  • regionID:domainID:key/key_id
  • key_id

In the preceding formats:

Default value:

  • If this parameter is not specified, the default master key will be used.
  • If there is no such a default master key, OBS will create one and use it by default.

Responses

Table 4 List of returned results

Type

Description

GetResult

Explanation:

SDK common results

Table 5 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits ranging from 2xx (indicating successes) to 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description.

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server.

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, this parameter value is null. The value varies with the API being called. For details, see Bucket-Related APIs (SDK for Python) and Object-Related APIs (SDK for Python).

Default value:

None

Table 6 GetResult.body

GetResult.body Type

Description

CopyPartResponse

Explanation:

Response to the request for copying a part. For details, see Table 7.

Table 7 CopyPartResponse

Parameter

Type

Description

etag

str

Explanation:

Base64-encoded 128-bit MD5 digest of a part. ETag is the unique identifier of the part content. It can be used to determine whether the part content is changed.

Value range:

The value must contain 32 characters.

Default value:

None

lastModified

str

Explanation:

Time when the last modification was made to the object

Restrictions:

The time must be in the GMT format, for example, Wed, 25 Mar 2020 02:39:52 GMT.

Default value:

None

sseKms

str

Explanation:

SSE-KMS is used for encrypting objects on the server side.

Value range:

kms

Default value:

None

sseKmsKey

str

Explanation:

ID of the KMS master key when SSE-KMS is used

Value range:

Valid value formats are as follows:

  1. regionID:domainID:key/key_id
  2. key_id

In the preceding formats:

Default value:

  • If this parameter is not specified, the default master key will be used.
  • If there is no such a default master key, OBS will create one and use it by default.

sseC

str

Explanation:

Algorithm used to encrypt and decrypt objects with SSE-C

Value range:

AES256

Default value:

None

sseCKeyMd5

str

Explanation:

MD5 value of the key for encrypting objects when SSE-C is used. This value is used to check whether any error occurs during the transmission of the key.

Restrictions:

The value is encrypted by MD5 and then encoded by Base64, for example, 4XvB3tbNTN+tIEVa0/fGaQ==.

Default value:

None

Code Examples

This example copies parts from one bucket to another.

 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
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/intl/en-us/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 CN-Hong Kong as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# 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 part number, which ranges from 1 to 10,000
    partNumber = "your partNumber"
    # Specify the ID of the multipart upload.
    uploadId = "your uploadid"
    # Specify the source bucket, source object, and source object version ID which can be null. The format is Source bucket name/Source object name?versionId=SourceObjectVersionId.
    copySource = 'sourcebucketname/sourceobjectkey'
    # Specify the copy scope in the format of x-y. Value range: [0, source object length – 1].
    # copySourceRange = '0-15'
    # Copy the part to the specified bucket using the multipart upload ID.
    resp = obsClient.copyPart(bucketName, objectKey, partNumber, uploadId, copySource)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Copy Part Succeeded')
        print('requestId:', resp.requestId)
        print('etagValue:', resp.body.etagValue)
        print('modifiedDate:', resp.body.modifiedDate)
    else:
        print('Copy Part Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Copy Part Failed')
    print(traceback.format_exc())