Este tópico descreve como inicializar o SDK do Object Storage Service (OSS) para Python.
Observações de uso
Antes de inicializar o SDK do OSS para Python, configure as credenciais de acesso. Neste tópico, utilizamos variáveis de ambiente para obter as credenciais de acesso. Para mais informações, consulte Configure access credentials using OSS SDK for Python 1.0.
Para obter informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.
Para criar um par de AccessKey para um usuário RAM, consulte Create an AccessKey pair.
-
A maioria das operações do SDK do OSS para Python baseia-se nas classes oss2.Service e oss2.Bucket.
A classe oss2.Service lista buckets.
A classe oss2.Bucket faz upload, download 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 em que o bucket está localizado. A classe oss2.Service não suporta o acesso a buckets por meio de nomes de domínio personalizados mapeados para esses buckets.
Pré-requisitos
Antes de configurar o cliente, configure as variáveis de ambiente com o par de AccessKey de um usuário RAM.
Linux
-
Execute os seguintes comandos na CLI para adicionar as configurações das variáveis de ambiente ao arquivo
~/.bashrc:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Aplique as alterações.
source ~/.bashrc -
Verifique se as variáveis de ambiente estão em vigor:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Execute o seguinte comando no terminal para visualizar o tipo de shell padrão:
echo $SHELL-
Configure as variáveis de ambiente com base no tipo de shell padrão.
Zsh
-
Execute os seguintes comandos para adicionar as configurações das variáveis de ambiente ao arquivo
~/.zshrc:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Aplique as alterações.
source ~/.zshrc -
Verifique se as variáveis de ambiente estão em vigor:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Execute os seguintes comandos para adicionar as configurações das variáveis de ambiente ao arquivo
~/.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 as alterações.
source ~/.bash_profile -
Verifique se as variáveis de ambiente estão em vigor:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Execute os seguintes comandos no CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Verifique se as variáveis de ambiente estão em vigor:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Execute os seguintes comandos no 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)-
Verifique se as variáveis de ambiente estão em vigor:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Exemplos padrão
Esta seção apresenta exemplos de uso dos algoritmos de assinatura V4 e V1 para inicializar o SDK do OSS para Python.
Observe que o código de exemplo a seguir usa 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 apresenta exemplos de configuração para cenários comuns. Por padrão, o código de exemplo usa o algoritmo de assinatura V4 e o par de AccessKey do usuário RAM para inicializar o SDK do OSS para Python.
Usar um endpoint interno para inicializar o SDK do OSS para Python
Se suas aplicações estiverem implantadas em uma instância ECS e você precisar acessar frequentemente os dados do OSS em um bucket na mesma região da instância ECS, use um endpoint interno para reduzir significativamente a latência de rede e os custos de largura de banda.
O código a seguir demonstra 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 SDK do OSS para Python
Se você tiver vários buckets para diferentes finalidades, poderá especificar subdomínios distintos para cada bucket, o que facilita o gerenciamento e a organização dos recursos.
O exemplo abaixo ilustra como configurar uma instância OSSClient com um nome de domínio personalizado.
Primeiro, mapeie o nome de domínio personalizado para o nome de domínio padrão do bucket. Caso contrário, ocorrerá um erro. Para mais informações sobre como mapear um nome de domínio personalizado para o nome de domínio padrão de um 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)
Configurar o tempo limite de conexão
O código a seguir demonstra como configurar 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 o CRC-64
Por padrão, o CRC-64 fica ativado para garantir a integridade dos dados durante o upload ou o download de objetos.
Não recomendamos desativar o CRC-64. Se você desativar o CRC-64, a integridade dos dados poderá ficar comprometida durante o upload ou o download de objetos.
O exemplo de código abaixo ilustra 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)
Especificar o tamanho do pool de conexões
O código a seguir demonstra como especificar 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
Diferentes versões do Transport Layer Security (TLS) possuem recursos de segurança e desempenho distintos. Selecione uma versão do TLS com base no seu cenário.
Você pode especificar a versão do TLS a partir da versão 2.18.1 do SDK do OSS para Python.
O exemplo abaixo ilustra como definir 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 descreve os parâmetros configuráveis ao inicializar a classe oss2.Bucket.
|
Parâmetro |
Exemplo |
Descrição |
Método |
|
is_cname |
True |
Especifica 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. Indica o início de uma nova sessão. Valor padrão: None. Se você definir este parâmetro com o nome de uma sessão existente, o sistema a reutilizará. |
oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region) |
|
connect_timeout |
30 |
O tempo limite de uma conexão. Valor padrão: 60. Unidade: segundos. |
oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30, region=region) |
|
app_name |
mytool |
Nome do aplicativo que utiliza o SDK do OSS para Python. Por padrão, este parâmetro fica em branco. Se não estiver vazio, especifique o valor correspondente no campo User-Agent. Importante
A string atua como valor de cabeçalho HTTP e deve obedecer aos padrões HTTP. |
oss2.Bucket(auth, endpoint, 'examplebucket', app_name='mytool', region=region) |
|
enable_crc |
False |
Define se o CRC-64 fica ativado.
|
oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False, region=region) |