Todos los productos
Search
Centro de documentos

:Inicialización

Última actualización: Sep 03, 2026

Este tema describe cómo inicializar Object Storage Service (OSS) SDK para Python.

Notas de uso

  • Antes de inicializar OSS SDK para Python, debe configurar las credenciales de acceso. En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Si desea obtener información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • Si desea crear un par de AccessKey para un usuario de RAM, consulte Create an AccessKey pair.

  • La mayoría de las operaciones de OSS SDK para Python se realizan mediante las clases oss2.Service y oss2.Bucket.

    • La clase oss2.Service se utiliza para listar buckets.

    • La clase oss2.Bucket se utiliza para cargar, descargar y eliminar objetos, así como para configurar buckets.

    Al inicializar las clases oss2.Service y oss2.Bucket, debe especificar el endpoint de la región donde se encuentra el bucket. La clase oss2.Service no admite el acceso a buckets mediante nombres de dominio personalizados asignados a dichos buckets.

Requisitos previos

Aviso

Antes de configurar el cliente, asegúrese de haber configurado las variables de entorno mediante el par de AccessKey de un usuario de RAM.

Linux

  1. Ejecute los siguientes comandos en la CLI para agregar las configuraciones de las variables de entorno al archivo ~/.bashrc:

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    1. Aplique los cambios.

      source ~/.bashrc
    2. Compruebe si las variables de entorno han surtido efecto:

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Ejecute el siguiente comando en la terminal para ver el tipo de shell predeterminado:

    echo $SHELL
    1. Configure las variables de entorno según el tipo de shell predeterminado.

      Zsh

      1. Ejecute los siguientes comandos para agregar las configuraciones de las variables de entorno al archivo ~/.zshrc:

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Aplique los cambios.

        source ~/.zshrc
      3. Compruebe si las variables de entorno han surtido efecto:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Ejecute los siguientes comandos para agregar las configuraciones de las variables de entorno al archivo ~/.bash_profile:

        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. Aplique los cambios.

        source ~/.bash_profile
      3. Compruebe si las variables de entorno han surtido efecto:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Ejecute los siguientes comandos en CMD:

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    1. Compruebe si las variables de entorno surten efecto:

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. Ejecute los siguientes comandos en 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)
    1. Compruebe si la variable de entorno surte efecto:

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Ejemplos predeterminados

Esta sección proporciona ejemplos sobre cómo usar el algoritmo de firma V4 y el algoritmo de firma V1 para inicializar OSS SDK para Python.

Tenga en cuenta que el siguiente código de ejemplo utiliza el endpoint público del bucket y el par de AccessKey del usuario de RAM.

(Recomendado) Uso del algoritmo de firma V4

Importante
  • Cuando utilice el algoritmo de firma V4 para inicializar OSS SDK para Python, debe especificar el endpoint. En este ejemplo, se usa el endpoint público https://oss-cn-hangzhou.aliyuncs.com de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre los endpoints públicos de otras regiones, consulte Regions and endpoints.

  • Si utiliza el algoritmo de firma V4, debe especificar un ID de región de Alibaba Cloud como identificador de la región donde se inicia la solicitud. En este ejemplo, se usa el ID de región cn-hangzhou de la región China (Hangzhou). Para obtener más información sobre los IDs de región de otras regiones, consulte Regions and endpoints.

El siguiente código de ejemplo muestra cómo usar el algoritmo de firma V4 para inicializar OSS SDK para Python mediante un endpoint de OSS:

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

(No recomendado) Uso del algoritmo de firma V1

Importante

El siguiente código de ejemplo muestra cómo usar el algoritmo de firma V1 para inicializar OSS SDK para Python mediante un endpoint de OSS:

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

Ejemplos de configuración en escenarios comunes

Esta sección proporciona ejemplos de configuración en escenarios comunes. El código de ejemplo utiliza el algoritmo de firma V4 y el par de AccessKey del usuario de RAM para inicializar OSS SDK para Python de forma predeterminada.

Uso de un endpoint interno para inicializar OSS SDK para Python

Si sus aplicaciones están desplegadas en una instancia de ECS y necesita acceder con frecuencia a datos de OSS en un bucket de la misma región que la instancia de ECS, utilice un endpoint interno para reducir significativamente la latencia de red y los costos de ancho de banda.

El siguiente código de ejemplo muestra cómo usar un endpoint interno para configurar una instancia de OSSClient:

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

Uso de un nombre de dominio personalizado para inicializar OSS SDK para Python

Si tiene varios buckets para diferentes usos, puede especificar distintos subdominios para cada bucket y así gestionar y organizar mejor los recursos.

El siguiente código de ejemplo muestra cómo usar un nombre de dominio personalizado para configurar una instancia de OSSClient.

Aviso

Primero debe asignar el nombre de dominio personalizado al nombre de dominio predeterminado del bucket. De lo contrario, se reportará un error. Para obtener más información sobre cómo asignar un nombre de dominio personalizado al nombre de dominio predeterminado de un bucket, consulte Access OSS through a custom domain name.

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

Configuración del tiempo de espera de conexión

El siguiente código de ejemplo muestra cómo configurar el tiempo de espera de conexión:

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

Deshabilitar CRC-64

De forma predeterminada, CRC-64 está habilitado para garantizar la integridad de los datos cuando carga o descarga objetos.

Aviso

Se recomienda no deshabilitar CRC-64. Si deshabilita CRC-64, la integridad de los datos podría verse afectada al cargar o descargar objetos.

El siguiente código de ejemplo muestra cómo deshabilitar 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)                   

Especificación del tamaño del pool de conexiones

El siguiente código de ejemplo muestra cómo especificar el tamaño del pool de conexiones:

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

Especificación de la versión de TLS

Las diferentes versiones de Transport Layer Security (TLS) tienen distintas características de seguridad y rendimiento. Seleccione una versión de TLS según su escenario.

Nota

Puede especificar la versión de TLS en OSS SDK para Python 2.18.1 o posterior.

El siguiente código de ejemplo muestra cómo establecer la versión de TLS en 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")

Parámetros admitidos por la clase oss2.Bucket

La siguiente tabla describe los parámetros que puede configurar al inicializar la clase oss2.Bucket.

Parámetro

Ejemplo

Descripción

Método

is_cname

True

Especifica si el endpoint es un nombre de dominio personalizado. Valores válidos:

  • True

  • False (predeterminado)

oss2.Bucket(auth, cname, 'examplebucket', is_cname=True, region=region)

session

mytestsession

El nombre de la sesión, que especifica que se inicia una nueva sesión. Valor predeterminado: None. Si establece este parámetro con el nombre de una sesión existente, se reutiliza dicha sesión.

oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region)

connect_timeout

30

El tiempo de espera de una conexión. Valor predeterminado: 60. Unidad: segundos.

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

app_name

mytool

El nombre de la aplicación que usa OSS SDK para Python. De forma predeterminada, este parámetro se deja vacío. Si el parámetro no está vacío, especifique el valor correspondiente en el campo User-Agent.

Importante

La cadena se pasa como un valor de encabezado HTTP y debe cumplir con los estándares HTTP.

oss2.Bucket(auth, endpoint, 'examplebucket', app_name='mytool', region=region)

enable_crc

False

Especifica si se habilita CRC-64.

  • True (predeterminado)

  • False

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

Preguntas frecuentes

Si deseo acceder a OSS mediante otros servicios de Alibaba Cloud en la misma región donde se encuentra el bucket, ¿puedo usar un endpoint interno para acelerar la transferencia de datos?

Sí, puede usar un endpoint interno para acelerar la transferencia de datos. Si tiene requisitos de transferencia de datos, se recomienda acceder a OSS mediante otros servicios de Alibaba Cloud, como instancias de ECS, en la misma región que OSS. Para obtener más información, consulte Access from ECS instances within the same region.

¿Cómo consulto el AccessKey ID de un usuario de RAM? ¿Puedo consultar el AccessKey secret de un par de AccessKey antiguo?

  1. Para consultar el AccessKey ID de un usuario de RAM, inicie sesión en la consola de RAM.

  2. El AccessKey secret de un usuario de RAM solo se muestra cuando se crea el par de AccessKey. No puede consultar el par de AccessKey posteriormente. Si olvida el AccessKey secret, no podrá recuperarlo. Puede seleccionar directamente un usuario de RAM específico en la consola de RAM y crear un nuevo par de AccessKey para su rotación. Para obtener más información, consulte Create an AccessKey pair.

Si se reporta un error, ¿cómo determino el tipo específico de error?

OSS proporciona Error codes para ayudarle a determinar el tipo específico de un error. Por ejemplo, consulte 02-AUTH para ver errores de autenticación comunes.