All Products
Search
Document Center

:Initialization

Last Updated:Jan 24, 2025

This topic describes how to initialize Object Storage Service (OSS) SDK for Python.

Usage notes

  • Before you initialize OSS SDK for Python, you must configure access credentials. In this topic, access credentials are obtained from environment variables. For more information, see Configure access credentials.

  • If you want to obtain information about OSS regions and endpoints, see Regions and endpoints.

  • If you want to create an AccessKey pair for a RAM user, see Create an AccessKey pair.

  • Most operations of OSS SDK for Python are performed based on the oss2.Service and oss2.Bucket classes.

    • The oss2.Service class is used to list buckets.

    • The oss2.Bucket class is used to upload, download, and delete objects, and configure buckets.

    When you initialize the oss2.Service and oss2.Bucket classes, you must specify the endpoint of the region in which the bucket is located. The oss2.Service class does not support access to buckets by using custom domain names that are mapped to the buckets.

Prerequisites

Warning

Before you configure the client, you have configured the environment variables by using the AccessKey pair of a RAM user.

Linux

  1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Run the following command to apply the changes:

    source ~/.bashrc
  3. Run the following commands to check whether the environment variables take effect:

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Run the following command in the terminal to view the default shell type:

    echo $SHELL
  2. Configure environment variables based on the default shell type.

    Zsh

    1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Run the following command to apply the changes:

      source ~/.zshrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    Bash

    1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. Run the following command to apply the changes:

      source ~/.bash_profile
    3. Run the following commands to check whether the environment variables take effect:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Run the following commands in CMD:

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Run the following commands to check whether the environment variables take effect:

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. Run the following commands in PowerShell:

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Run the following commands to check whether the environment variable takes effect:

    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Default examples

This section provides examples on how to use the V4 signature algorithm and the V1 signature algorithm to initialize OSS SDK for Python.

Note that the following sample code uses the public endpoint of the bucket and the AccessKey pair of the RAM user.

(Recommended) Use the V4 signature algorithm

Important
  • When you use the V4 signature algorithm to initialize OSS SDK for Python, you must specify the endpoint. In this example, the public endpoint https://oss-cn-hangzhou.aliyuncs.com of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the public endpoints of other regions, see Regions and endpoints.

  • If you use the V4 signature algorithm, you must specify an Alibaba Cloud Region ID as the identifier of the region in which the request is initiated. In this example, the region ID cn-hangzhou of the China (Hangzhou) region is used. For more information about the region IDs of other regions, see Regions and endpoints.

The following sample code provides an example on how to use the V4 signature algorithm to initialize OSS SDK for Python by using an OSS endpoint:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region) 

(Not recommended) Use the V1 signature algorithm

Important

From March 1, 2025, the V1 signature algorithm of OSS is no longer available to new customers with new UIDs. From September 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.

The following sample code provides an example on how to use the V1 signature algorithm to initialize OSS SDK for Python by using an OSS endpoint:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket')                    

Configuration examples in common scenarios

This section provides configuration examples in common scenarios. The sample code uses the V4 signature algorithm and the AccessKey pair of the RAM user to initialize OSS SDK for Python by default.

Use an internal endpoint to initialize OSS SDK for Python

If your applications are deployed on an ECS instance and you need to frequently access OSS data in a bucket in the same region as the ECS instance, use an internal endpoint to significantly reduce network latency and bandwidth costs.

The following sample code provides an example on how to use an internal endpoint to configure an OSSClient instance:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region) 

Use a custom domain name to initialize OSS SDK for Python

If you have multiple buckets for different usage, you can specify different subdomains for each bucket to better manage and organize resources.

The following sample code provides an example on how to use a custom domain name to configure an OSSClient instance.

Warning

You must first map the custom domain name to the default domain name of the bucket. Otherwise, an error is reported. For more information about how to map a custom domain name to the default domain name of a bucket, see Map a custom domain name to the default domain name of a bucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
// Specify a custom domain name. Example: https://static.example.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. Set is_cname to true to enable CNAME.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', is_cname=True, region=region) 

Configure the connection timeout period

The following sample code provides an example on how to configure the connection timeout period:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket and set the connection timeout period to 30 seconds. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30,region=region)                    

Disable CRC-64

By default, CRC-64 is enabled to ensure data integrity when you upload or download objects.

Warning

We recommend that you do not disable CRC-64. If you disable CRC-64, data integrity may be affected when you upload or download objects.

The following sample code provides an example on how to disable CRC-64:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket and set enable_crc to False to disable CRC-64. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False,region=region)                   

Specify the connection pool size

The following sample code provides an example on how to specify the connection pool size:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the connection pool size. Default value: 10. 
session = oss2.Session(pool_size=20)

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session,region=region)

Specify the TLS version

Different Transport Layer Security (TLS) versions have different security and performance features. Select a TLS version based on your scenario.

Note

You can specify the TLS version in OSS SDK for Python 2.18.1 or later.

The following sample code provides an example on how to set the TLS version to 1.2:

# -*- coding: utf-8 -*-
import ssl
import oss2
from requests.adapters import HTTPAdapter
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Configure the SSL adapter. 
class SSLAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        # Set the TLS version to 1.2. 
        kwargs["ssl_version"] = ssl.PROTOCOL_TLSv1_2
        return super().init_poolmanager(*args, **kwargs)

# Create a session object and configure the adapter by using the session object. 
session = oss2.Session(adapter=SSLAdapter())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session, region=region)

# Upload an object. 
bucket.put_object("example.txt", "hello")

Parameters supported by the oss2.Bucket class

The following table describes the parameters that you can configure when you initialize the oss2.Bucket class.

Parameter

Example

Description

Method

is_cname

True

Specifies whether the endpoint is a custom domain name. Valid values:

  • True

  • False (default)

oss2.Bucket(auth, cname, 'examplebucket', is_cname=True, region=region)

session

mytestsession

The name of the session, which specifies that a new session is started. Default value: None. If you set this parameter to the name of an existing session, the session is reused.

oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region)

connect_timeout

30

The timeout period of a connection. Default value: 60. Unit: seconds.

oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30, region=region)

app_name

mytool

The name of the application that uses OSS SDK for Python. By default, this parameter is left empty. If the parameter is not empty, specify the corresponding value in the User-Agent field.

Important

The string is passed as an HTTP header value and must comply with HTTP standards.

oss2.Bucket(auth, endpoint, 'examplebucket', app_name='mytool', region=region)

enable_crc

False

Specifies whether to enable CRC-64.

  • True (default)

  • False

oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False, region=region)

FAQ

If you want to access OSS by using other Alibaba Cloud services in the same region in which the bucket is located, can I use an internal endpoint to accelerate data transfer?

Yes, you can use an internal endpoint to accelerate data transfer. If you have requirements on data transfer, we recommend that you access OSS by using other Alibaba Cloud services, such as ECS instances, in the same region as OSS. For more information, see Access from ECS instances within the same region.

How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an old AccessKey pair?

  1. To view the AccessKey ID of a RAM user, log on to the RAM console.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. You can directly select a specific RAM user in the RAM console and create a new AccessKey pair for rotation. For more information, see Create an AccessKey pair.

If an error is reported, how do I determine the specific type of the error?

OSS provides Error codes to help you determine the specific type of an error. For example, see 02-AUTH for common authentication errors.