Copy files (Python SDK V2)
This topic describes how to copy an object in a bucket for which versioning is enabled. You can call the CopyObject method to copy an object that is smaller than 1 GB and call the UploadPartCopy method to copy an object that is larger than 1 GB.
Notes
-
The sample code in this topic uses the region ID
cn-hangzhoufor the China (Hangzhou) region. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints. -
To copy files, you must have the
oss:GetObjectandoss:PutObjectpermissions. For more information, see Attach a custom policy to a RAM user.
Sample code
Copy an object
To copy an object that is smaller than 1 GB, you can call the CopyObject method to copy the object from a source bucket to a destination bucket in the same region.
-
By default, x-oss-copy-source copies the current version of an object. If the current version is a delete marker, OSS returns a 404 Not Found error. You can add versionId to x-oss-copy-source to copy a specific version of the object. Delete markers cannot be copied.
-
You can copy an earlier version of an object to the same bucket. The copied version becomes the new current version, which restores the earlier version of the object.
-
If versioning is enabled for the destination bucket, OSS automatically generates a unique version ID for the copied object. This version ID is returned in the x-oss-version-id header of the response. If versioning is disabled or suspended for the destination bucket, OSS generates a version with a null version ID for the copied object and overwrites the previous version that has a null version ID.
-
You cannot copy an appendable object to a destination bucket for which versioning is enabled or suspended.
You can use the following code to copy an object.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the purpose of the script: copy an object in a bucket.
parser = argparse.ArgumentParser(description="copy object sample")
# Define command-line arguments, including the required region, destination bucket name, source bucket name, destination object name, source object name, source object version ID, and optional endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the destination object.', required=True)
parser.add_argument('--source_key', help='The name of the source object.', required=True)
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--source_version_id', help='The version ID of the source object.',required=True)
def main():
# Parse command-line arguments to obtain the values entered by the user.
args = parser.parse_args()
# Load access credential information from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default SDK configurations to create a configuration object and set the authentication provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region property of the configuration object based on the command-line arguments.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
client = oss.Client(cfg)
# Send a request to copy the specified object.
result = client.copy_object(oss.CopyObjectRequest(
bucket=args.bucket, # Destination bucket name.
key=args.key, # Destination object name.
source_key=args.source_key, # Source object name.
source_bucket=args.source_bucket, # Source bucket name.
source_version_id=args.source_version_id, # Version ID of the source object.
))
# Print the information about the operation result to confirm the request status.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' version id: {result.version_id},'
f' hash crc64: {result.hash_crc64},'
f' source version id: {result.source_version_id},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' last modified: {result.last_modified},'
f' etag: {result.etag},'
)
# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script. The program flow starts here.
Multipart copy
For objects larger than 1 GB, you must use multipart copy (UploadPartCopy).
-
By default, the UploadPartCopy operation copies a part from the current version of an existing object. You can copy a specific version of an object by including the SourceVersionId parameter in the UploadPartCopyRequest request.
-
If you do not specify a version ID and the current version of the source object is a delete marker, OSS returns a 404 Not Found error. If you specify a version ID that corresponds to a delete marker, OSS returns a 400 Bad Request error.
You can use the following code to copy an object using multipart copy.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the purpose of the script: synchronously perform a multipart copy upload.
parser = argparse.ArgumentParser(description="upload part copy synchronously sample")
# Add the --region command-line argument to specify the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument to specify the name of the destination bucket. This is a required parameter.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument to specify the domain name that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument to specify the name of the destination object. This is a required parameter.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --source_bucket command-line argument to specify the name of the source bucket. This is a required parameter.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
# Add the --source_key command-line argument to specify the name of the source object. This is a required parameter.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Add the --source_version_id command-line argument to specify the version ID of the source object. This is a required parameter.
parser.add_argument('--source_version_id', help='The version id of the source object.', required=True)
def main():
# Parse the command-line arguments to obtain the values entered by the user.
args = parser.parse_args()
# Load the credentials required to access OSS from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default SDK configurations to create a configuration object and set the authentication provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
client = oss.Client(cfg)
# Obtain the metadata of the source object, including the file size and other information.
result_meta = client.get_object_meta(oss.GetObjectMetaRequest(
bucket=args.source_bucket,
key=args.source_key,
))
# Initiate a multipart upload task and return an UploadId to identify this process.
result = client.initiate_multipart_upload(oss.InitiateMultipartUploadRequest(
bucket=args.bucket,
key=args.key,
))
# Define the size of each part (set to 1 MB here).
part_size = 1024 * 1024
total_size = result_meta.content_length # The total size of the source file.
part_number = 1 # The part number starts from 1.
upload_parts = [] # Used to store information about uploaded parts.
offset = 0 # The current byte offset.
# Loop until all data is uploaded.
while offset < total_size:
num_to_upload = min(part_size, total_size - offset) # Calculate the amount of data to upload this time.
end = offset + num_to_upload - 1 # Determine the end position.
# Perform the actual multipart copy upload operation.
up_result = client.upload_part_copy(oss.UploadPartCopyRequest(
bucket=args.bucket,
key=args.key,
upload_id=result.upload_id,
part_number=part_number,
source_bucket=args.source_bucket,
source_key=args.source_key,
source_version_id=args.source_version_id, # Replace this with the actual version ID.
source_range=f'bytes={offset}-{end}', # Specify the range in the source object.
))
# Print the status information of the part upload.
print(f'status code: {up_result.status_code},'
f' request id: {up_result.request_id},'
f' part number: {part_number},'
f' last modified: {up_result.last_modified},'
f' etag: {up_result.etag},'
f' source version id: {up_result.source_version_id},'
)
# Record the information of the successfully uploaded part.
upload_parts.append(oss.UploadPart(part_number=part_number, etag=up_result.etag))
offset += num_to_upload # Update the offset.
part_number += 1 # Update the part number.
# Sort all uploaded parts by their part numbers.
parts = sorted(upload_parts, key=lambda p: p.part_number)
# Send a request to the OSS service to complete the multipart upload.
result = client.complete_multipart_upload(oss.CompleteMultipartUploadRequest(
bucket=args.bucket,
key=args.key,
upload_id=result.upload_id,
complete_multipart_upload=oss.CompleteMultipartUpload(
parts=parts
)
))
# Print the detailed results after the upload is complete.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' bucket: {result.bucket},'
f' key: {result.key},'
f' location: {result.location},'
f' etag: {result.etag},'
f' encoding type: {result.encoding_type},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
)
# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script. The program flow starts here.
References
-
For the complete sample code for copying an object, see copy_object.py.
-
For the complete sample code for performing a multipart copy, see upload_part_copy.py.