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
Before you configure the client, you have configured the environment variables by using the AccessKey pair of a RAM user.
Linux
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:
source ~/.bashrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to view the default shell type:
echo $SHELL
Configure environment variables based on the default shell type.
Zsh
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:
source ~/.zshrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
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:
source ~/.bash_profile
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
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%
PowerShell
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.
(Not recommended) Use the V1 signature algorithm
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.
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.
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.
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:
| 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) |