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.
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Run the following command in the terminal to view the default shell type:
Configure environment variables based on the default shell type.
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
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
Run the following command to apply the changes:
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID%
echo %OSS_ACCESS_KEY_SECRET%
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)
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = 'yourEndpoint'
region = 'cn-hangzhou'
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
endpoint = 'yourEndpoint'
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = 'yourEndpoint'
region = 'cn-hangzhou'
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.
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
// Specify a custom domain name. Example: https://static.example.com.
endpoint = 'yourEndpoint'
region = 'cn-hangzhou'
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
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:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
session = oss2.Session(pool_size=20)
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:
import ssl
import oss2
from requests.adapters import HTTPAdapter
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
class SSLAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
kwargs["ssl_version"] = ssl.PROTOCOL_TLSv1_2
return super().init_poolmanager(*args, **kwargs)
session = oss2.Session(adapter=SSLAdapter())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session, region=region)
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 |
Parameter | Example | Description | Method |
is_cname | True | Specifies whether the endpoint is a custom domain name. Valid values: | 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. | 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?
To view the AccessKey ID of a RAM user, log on to the RAM console.
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.