Upload objects using OSS SDK for Python 2.0

Updated at:

This topic describes how to use Object Storage Service (OSS) SDK for Python V2 to upload objects to a versioning-enabled bucket.

Usage notes

In the sample code of this topic, the ID of the China (Hangzhou) region (cn-hangzhou) and the public endpoint are used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use the internal endpoint. For information about the mappings between OSS regions and endpoints, see Regions and endpoints.

Permissions

By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Uploads an object.

oss:PutObjectTagging

Required if you specify object tags by using the x-oss-tagging header when you upload an object.

kms:GenerateDataKey

Required if the X-Oss-Server-Side-Encryption: KMS header is set to KMS when you upload an object.

kms:Decrypt

Sample code

Simple upload

Note
  • If you upload an object to a versioning-enabled bucket, OSS generates a unique version ID for the object and includes the version ID in the x-oss-version-id response header.

  • If you upload an object to a versioning-suspended bucket, the version ID generated for the object is null. If you upload an object with the same name as an existing object to a versioning-suspended bucket, the existing object is overwritten. This way, each object has only a single version whose version ID is null.

The following sample code provides an example of how to perform a simple upload:

import argparse
import requests
import alibabacloud_oss_v2 as oss

# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Configure the --region command line argument to specify the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Configure the --bucket command line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Configure the --endpoint command line argument to specify the endpoint that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Configure the --key command line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line arguments.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Obtain the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Upload a local file.
    local_file_path = '/yourLocalFilePath/yourFileName'
    with open(local_file_path, 'rb') as file:
        data = file.read()

    # Execute the request to upload an object, and specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
    ))

    # Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The entry point of the script. Call the main() function when the script is directly run.

Append upload

In a versioning-enabled bucket, the AppendObject operation can be performed only on the current version of an appendable object.

Note
  • When you perform the AppendObject operation on the current version of an appendable object, OSS does not generate a previous version for the object.

  • When you perform the PutObject or DeleteObject operation on the current version of an appendable object, OSS saves the appendable object as a previous version that can no longer be appended.

  • The AppendObject operation cannot be performed on the current version of a non-appendable object such as a normal object or a delete marker.

The following sample code provides an example of how to perform an append upload:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. Sample description: An example showing how to append data to an object in an OSS bucket.
parser = argparse.ArgumentParser(description="append object sample")

# Add command line arguments.
# --region: Specify the region where the OSS bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# --bucket: Specify the name of the bucket to operate on. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# --endpoint: Specify the endpoint used to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# --key: Specify the key name of the object (file) in OSS. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command line arguments.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication to ensure operation security and flexibility.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations provided by the SDK.
    cfg = oss.config.load_default()

    # Specify the previously created configuration object as the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region where the OSS client is located based on user input.
    cfg.region = args.region

    # If the user provides a custom endpoint, update the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSSClient instance using the configurations above to interact with OSS.
    client = oss.Client(cfg)

    # Specify the data that you want to append.
    data1 = b'hello'  # The data for the first append operation.
    data2 = b' world'  # The data for the second append operation.

    # Append data for the first time.
    result = client.append_object(oss.AppendObjectRequest(
        bucket=args.bucket,  # Specify the destination bucket.
        key=args.key,  # Specify the key name of the object.
        position=0,  # Specify the position from which the append operation starts. Set the value to 0.
        body=data1,  # Specify the data that you want to append.
    ))

    # Display the result of the first append operation.
    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' next position: {result.next_position},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
    )

    # Append data for the second time.
    result = client.append_object(oss.AppendObjectRequest(
        bucket=args.bucket,  # Specify the destination bucket.
        key=args.key,  # Specify the key name of the object.
        position=result.next_position,  # Specify that the append operation starts from the next position after the previous append operation.
        body=data2,  # Specify the data that you want to append.
    ))

    # Display the result of the second append operation.
    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' next position: {result.next_position},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
    )

# Call the main() function when the script is directly run.
if __name__ == "__main__":
    main()  # The entry point of the script. The control flow starts from here.

Multipart upload

Note

In a versioning-enabled bucket, when you call the CompleteMultipartUpload operation to complete the multipart upload task for the entire object, OSS generates a unique version ID for the entire object and includes the version ID in the x-oss-version-id response header.

The following sample code provides an example of how to perform a multipart upload:

import os
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the purpose of the script. Sample description: An example showing how to perform multipart upload in an OSS bucket.
parser = argparse.ArgumentParser(description="multipart upload sample")

# Configure the --region command line argument to specify the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Configure the --bucket command line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Configure the --endpoint command line argument to specify the endpoint that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Specify the --key command line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

# Specify the --file_path command line argument to specify the path of the file that you want to upload. This argument is required.
parser.add_argument('--file_path', help='The path of Upload file.', required=True)

def main():
    # Parse the command line arguments.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication to ensure operation security and flexibility.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations provided by the SDK.
    cfg = oss.config.load_default()

    # Specify the previously created configuration object as the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region where the OSS client is located based on user input.
    cfg.region = args.region

    # If the user provides a custom endpoint, update the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSSClient instance using the configurations above to interact with OSS.
    client = oss.Client(cfg)

    # Initiate the multipart upload request and obtain the upload ID for subsequent multipart upload operations.
    result = client.initiate_multipart_upload(oss.InitiateMultipartUploadRequest(
        bucket=args.bucket,
        key=args.key,
    ))

    # Set the part size to 5 MB.
    part_size = 5 * 1024 * 1024

    # Obtain the total size of the file that you want to upload.
    data_size = os.path.getsize(args.file_path)

    # Initialize the part number, starting from 1.
    part_number = 1

    # Store the result of each uploaded part.
    upload_parts = []

    # Open the file and read it in binary mode.
    with open(args.file_path, 'rb') as f:
        # Traverse the file and upload it based on the part size.
        for start in range(0, data_size, part_size):
            n = part_size
            if start + n > data_size:  # Handle the case where the size of the last part may be smaller than the specified part size.
                n = data_size - start

            # Create SectionReader to read a specific part of the file.
            reader = oss.io_utils.SectionReader(oss.io_utils.ReadAtReader(f), start, n)

            # Upload the parts.
            up_result = client.upload_part(oss.UploadPartRequest(
                bucket=args.bucket,
                key=args.key,
                upload_id=result.upload_id,
                part_number=part_number,
                body=reader
            ))

            # Display the result of each uploaded part.
            print(f'status code: {up_result.status_code},'
                  f' request id: {up_result.request_id},'
                  f' part number: {part_number},'
                  f' content md5: {up_result.content_md5},'
                  f' etag: {up_result.etag},'
                  f' hash crc64: {up_result.hash_crc64},'
                  )

            # Save the part upload result to the list.
            upload_parts.append(oss.UploadPart(part_number=part_number, etag=up_result.etag))

            # Increment the part number.
            part_number += 1

    # Sort the uploaded parts by part number.
    parts = sorted(upload_parts, key=lambda p: p.part_number)

    # Send a request to complete the multipart upload and merge all parts into a complete object.
    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
        )
    ))

    # Display the result of multipart upload.
    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},'
    )

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main()  # The entry point of the script. The control flow starts from here.