Este tópico descreve como inicializar o Object Storage Service (OSS) SDK for Python.
Observações de uso
Antes de inicializar o OSS SDK for Python, configure as credenciais de acesso. Neste tópico, as credenciais são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso (Python SDK V1).
Para obter informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey.
-
A maioria das operações do OSS SDK for Python utiliza as classes oss2.Service e oss2.Bucket.
A classe oss2.Service lista buckets.
A classe oss2.Bucket realiza upload, baixe e exclusão de objetos, além de configurar buckets.
Ao inicializar as classes oss2.Service e oss2.Bucket, especifique o endpoint da região onde o bucket está localizado. A classe oss2.Service não permite acesso a buckets por nomes de domínio personalizados mapeados para eles.
Pré-requisitos
Antes de configurar o cliente, verifique se as variáveis de ambiente já foram configuradas com o par de AccessKey de um usuário RAM.
Exemplos padrão
Esta seção apresenta exemplos de uso dos algoritmos de assinatura V4 e V1 para inicializar o OSS SDK for Python.
Os códigos de exemplo abaixo utilizam o endpoint público do bucket e o par de AccessKey do usuário RAM.
(Recomendado) Usar o algoritmo de assinatura V4
(Não recomendado) Usar o algoritmo de assinatura V1
Exemplos de configuração em cenários comuns
Esta seção traz exemplos de configuração para situações frequentes. Por padrão, os códigos utilizam o algoritmo de assinatura V4 e o par de AccessKey do usuário RAM para inicializar o OSS SDK for Python.
Usar um endpoint interno para inicializar o OSS SDK for Python
Se suas aplicações estiverem em uma instância ECS e precisarem acessar dados do OSS no mesmo bucket e região com frequência, utilize um endpoint interno. Essa abordagem reduz significativamente a latência de rede e os custos de largura de banda.
O exemplo a seguir mostra como configurar uma instância OSSClient com um endpoint interno:
# -*- 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)
Usar um nome de domínio personalizado para inicializar o OSS SDK for Python
Caso você tenha vários buckets com finalidades distintas, defina subdomínios diferentes para cada um deles. Isso facilita a gestão e a organização dos recursos.
O código abaixo ilustra como configurar uma instância OSSClient utilizando um nome de domínio personalizado.
Mapeie previamente o nome de domínio personalizado para o nome de domínio padrão do bucket. Caso contrário, ocorrerá um erro. Para saber como realizar esse mapeamento, consulte Acessar o OSS por meio de um nome de domínio personalizado.
# -*- 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)
Configurar o tempo limite de conexão
O exemplo abaixo demonstra como definir o tempo limite de conexão:
# -*- 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)
Desativar CRC-64
Por padrão, o CRC-64 vem ativado para garantir a integridade dos dados durante uploads e downloads de objetos.
Evite desativar o CRC-64. A desativação pode comprometer a integridade dos dados nas transferências de objetos.
Veja abaixo como desativar o 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)
Definir o tamanho do pool de conexões
O código a seguir exemplifica como ajustar o tamanho do pool de conexões:
# -*- 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)
Especificar a versão do TLS
Cada versão do Transport Layer Security (TLS) possui características próprias de segurança e desempenho. Escolha a versão adequada ao seu cenário.
A especificação da versão do TLS está disponível a partir da versão 2.18.1 do OSS SDK for Python.
O exemplo abaixo define a versão do TLS como 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 suportados pela classe oss2.Bucket
A tabela a seguir detalha os parâmetros configuráveis durante a inicialização da classe oss2.Bucket.
|
Parâmetro |
Exemplo |
Descrição |
Método |
|
is_cname |
True |
Indica se o endpoint é um nome de domínio personalizado. Valores válidos:
|
oss2.Bucket(auth, cname, 'examplebucket', is_cname=True, region=region) |
|
session |
mytestsession |
Nome da sessão, indicando o início de uma nova sessão. Valor padrão: None. Se definido com o nome de uma sessão existente, essa sessão será reutilizada. |
oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region) |
|
connect_timeout |
30 |
Tempo limite da conexão. Valor padrão: 60. Unidade: segundos. |
oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30, region=region) |
|
app_name |
mytool |
Nome da aplicação que utiliza o OSS SDK for Python. Por padrão, este campo fica vazio. Se preenchido, o valor aparecerá no campo User-Agent. Importante
A string é transmitida como valor de cabeçalho HTTP e deve seguir os padrões HTTP. |
oss2.Bucket(auth, endpoint, 'examplebucket', app_name='mytool', region=region) |
|
enable_crc |
False |
Define se o CRC-64 deve ser ativado.
|
oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False, region=region) |