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
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
-
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-
Aplique los cambios.
source ~/.bashrc -
Compruebe si las variables de entorno han surtido efecto:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Ejecute el siguiente comando en la terminal para ver el tipo de shell predeterminado:
echo $SHELL-
Configure las variables de entorno según el tipo de shell predeterminado.
Zsh
-
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 -
Aplique los cambios.
source ~/.zshrc -
Compruebe si las variables de entorno han surtido efecto:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
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 -
Aplique los cambios.
source ~/.bash_profile -
Compruebe si las variables de entorno han surtido efecto:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Ejecute los siguientes comandos en CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Compruebe si las variables de entorno surten efecto:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
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
(No recomendado) Uso del algoritmo de firma V1
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.
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.
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.
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:
|
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.
|
oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False, region=region) |