All Products
Search
Document Center

Object Storage Service:Initialization

Last Updated:Mar 12, 2024

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

Prerequisites

Access credentials are configured. For more information, see Configure access credentials.

Background information

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. For more information about endpoints, see Regions and endpoints and Map custom domain names.

Initialize the oss2.Service class

For more information, see List buckets.

Initialize the oss2.Bucket class

Use the V1 signature algorithm

Use the endpoint of the region in which the bucket is located to initialize the oss2.Bucket class

The following sample code provides an example on how to use the endpoint of the region in which the bucket is located to initialize the oss2.Bucket class: For more information about OSS endpoints of different regions, see Regions and endpoints.

# -*- 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')                    

Use a custom domain name that is mapped to a bucket to initialize the oss2.Bucket class

The following sample code provides an example on how to use a custom domain name that is mapped to a bucket to initialize the oss2.Bucket class: For more information, 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.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Specify the custom domain name that is mapped to the bucket. Example: example.com. 
cname = 'http://example.com'

# Specify the name of the bucket, and set is_cname to True to enable CNAME. CNAME is used to map a custom domain name to a bucket. 
bucket = oss2.Bucket(auth, cname, 'examplebucket', is_cname=True)   

Use anonymous access to initialize the oss2.Bucket class

Important

Anonymous users can read only buckets whose access control list (ACL) is public-read and read and write only buckets whose ACL is public-read-write. Anonymous users cannot perform operations that are related to the oss2.Service and oss2.Bucket classes.

The following sample code provides an example on how to initialize the oss2.Bucket class for the examplebucket bucket whose ACL is public-read-write:

# -*- coding: utf-8 -*-
import oss2

# 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. Example: examplebucket.     
bucket_name = 'examplebucket'

# Use anonymous access to initialize the oss2.Bucket class. 
bucket = oss2.Bucket(oss2.AnonymousAuth(), endpoint, bucket_name)

Use the V4 signature algorithm (recommended)

If you want to use the V4 signature algorithm which is more secure, you must specify the region information of the endpoint and declare oss2.ProviderAuthV4 during initialization. OSS SDK for Python 2.18.4 and later support V4 signatures.

The following sample code provides an example on how to use an OSS endpoint of the region in which the bucket is located to initialize the oss2.Bucket class and sign the request by using the V4 signature algorithm. For the sample code on how to use a custom domain name that is mapped to a bucket or use anonymous access to initialize the oss2.Bucket class, refer to the following sample code and change the variables.

# -*- 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) 

Parameters that are 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)

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())

connect_timeout

30

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

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

app_name

mytool

The name of the application that uses OSS SDK for Python. By default, this parameter is 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')

enable_crc

False

Specifies whether to enable CRC-64.

  • True (default)

  • False

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

Sample oss2.Bucket class configurations

This section provides examples on how to configure the oss2.Bucket class:

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.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 and set the connection timeout period to 30 seconds. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30)                    

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.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 and set enable_crc to False to disable CRC-64. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False)                   

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.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 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)

Specify the TLS version

Different 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 V2.18.1 or later.

The following sample 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.ProviderAuth(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 = 'yourEndpoint'

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

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

What to do next

After you initialize OSS SDK for Python, you can use the oss2.Service class and the oss2.Bucket class to initiate requests. For more information, see Get started with OSS SDK for Python.