GitHub | Guia do desenvolvedor do OSS SDK for Python 2.0 | Documentação do OSS SDK for Python 2.0
Início rápido
Pré-requisitos
É necessário ter o Python 3,8 ou superior.
Para verificar sua versão do Python, execute o comando python --version . Se o Python não estiver instalado ou se a versão for inferior a 3,8, baixe e instale o Python .
Instalar o SDK
-
Instale a versão mais recente para garantir que os exemplos de código funcionem corretamente.
pip install alibabacloud-oss-v2 -
Importe o pacote do SDK:
import alibabacloud_oss_v2 as oss
Configurar credenciais de acesso
Configure as credenciais com um par de AccessKey de um usuário RAM.
No console do RAM, crie um usuário RAM e selecione Using permanent AccessKey to access. Salve o par de AccessKey e conceda a permissão
AliyunOSSFullAccessao usuário.-
Use o par de AccessKey do usuário RAM para configurar as variáveis de ambiente.
Linux
-
Anexe as 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 as variáveis de ambiente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Verifique o tipo de shell padrão.
echo $SHELL-
Siga as etapas correspondentes ao seu tipo de shell.
Zsh
-
Anexe as 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 as variáveis de ambiente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Anexe as 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 as variáveis de ambiente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Defina as variáveis de ambiente no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Verifique as variáveis de ambiente.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Defina as variáveis de ambiente 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 as variáveis de ambiente.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Inicializar o cliente
Devido a uma alteração de política visando melhorar a conformidade e a segurança, a partir de 20 de março de 2025, novos usuários do OSS devem usar um nome de domínio personalizado (CNAME) para executar operações de API de dados em buckets do OSS localizados em regiões da China continental. Os endpoints públicos padrão estão restritos para essas operações. Consulte o anúncio oficial para obter a lista completa das operações afetadas. Se você acessar seus dados via HTTPS, é obrigatório vincular um certificado SSL válido ao seu domínio personalizado. Isso é obrigatório para acesso pelo OSS Console, pois o console impõe o uso de HTTPS.
Antes de executar o código de exemplo, substitua os espaços reservados, como<region-id>, pelos valores reais de região e endpoint , comoap-southeast-1.
Sync OSSClient
import alibabacloud_oss_v2 as oss
def main():
"""
Configuration details for initializing the Python SDK V2 client:
1. Signature version: The SDK uses Signature V4 by default for enhanced security.
2. Region configuration: When you initialize the client, you must specify an Alibaba Cloud region ID.
3. Endpoint configuration:
- You can use the endpoint parameter to specify a custom endpoint for service requests.
- If you do not specify an endpoint, the SDK automatically constructs a public endpoint based on the specified region.
4. Protocol configuration:
- The SDK uses HTTPS to construct the endpoint by default.
- To use HTTP, you must explicitly specify the protocol in the endpoint.
"""
# Load credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify only the region (Recommended).
# You must specify a region ID. The SDK automatically constructs an HTTPS endpoint based on the region.
cfg.region = '<region-id>'
# # Method 2: Specify both the region and the endpoint.
# # You must specify a region ID.
# cfg.region = '<region-id>'
# # Specify the public endpoint of the region where the bucket is located.
# cfg.endpoint = '<endpoint>'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Define the string to upload.
text_string = "Hello, OSS!"
data = text_string.encode('utf-8') # Encode the string as a UTF-8 byte string.
# Send a request to upload the object. Specify the bucket name, object key, and data.
result = client.put_object(oss.PutObjectRequest(
bucket="Your Bucket Name",
key="Your Object Key",
body=data,
))
# Print the status code, request ID, and ETag to verify that the request was successful.
print(f'status code: {result.status_code}\n'
f'request id: {result.request_id}\n'
f'etag: {result.etag}'
)
# When this script is run directly, call the main function.
if __name__ == "__main__":
main()
Async OSSClient
Requisitos do Async OSSClient:
alibabacloud-oss-v2: >= 1.2.0
Instalar aiohttp:
pip install aiohttp
import asyncio
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.aio as oss_aio
async def main():
"""
Configuration details for initializing the Python SDK V2 async client:
1. Signature version: The SDK uses Signature V4 by default for enhanced security.
2. Region configuration: When you initialize the AsyncClient, you must specify an Alibaba Cloud region ID.
3. Endpoint configuration:
- You can use the endpoint parameter to specify a custom endpoint for service requests.
- If you do not specify an endpoint, the SDK automatically constructs a public endpoint based on the specified region.
4. Protocol configuration:
- The SDK uses HTTPS to construct the endpoint by default.
- To use HTTP, you must explicitly specify the protocol in the endpoint.
5. Asynchronous features:
- Import the async module: import alibabacloud_oss_v2.aio as oss_aio
- Create an async client: oss_aio.AsyncClient(cfg)
- All operations require the await keyword.
- You must call await client.close() in a finally block to close the connection.
- You must install the aiohttp dependency: pip install aiohttp
"""
# Load credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify only the region (Recommended).
# You must specify a region ID. The SDK automatically constructs an HTTPS endpoint based on the region.
cfg.region = '<region-id>'
# # Method 2: Specify both the region and the endpoint.
# # You must specify a region ID.
# cfg.region = '<region-id>'
# # Specify the public endpoint of the region where the bucket is located.
# cfg.endpoint = '<endpoint>'
# Create an OSS async client with the specified configurations.
client = oss_aio.AsyncClient(cfg)
try:
# Define the string to upload.
text_string = "Hello, OSS!"
data = text_string.encode('utf-8') # Encode the string as a UTF-8 byte string.
# Send an async request to upload the object. Specify the bucket name, object key, and data.
# Note: Use the await keyword to wait for the async operation to complete.
result = await client.put_object(
oss.PutObjectRequest(
bucket="Your Bucket Name",
key="Your Object Key",
body=data,
)
)
# Print the status code, request ID, and ETag to verify that the request was successful.
print(f'status code: {result.status_code}\n'
f'request id: {result.request_id}\n'
f'etag: {result.etag}'
)
except Exception as e:
print(f'Upload failed: {e}')
finally:
# Close the async client connection to prevent resource leaks.
await client.close()
# When this script is run directly, call the main function.
if __name__ == "__main__":
# Use asyncio.run() to run the async main function.
asyncio.run(main())
Saída de upload bem-sucedido:
status code: 200
request id: 6875F95738B0ED3030F086A0
etag: "56AAD346F0899BFE8BDD02C06BBE511E"
Configuração do cliente
Nome de domínio personalizado
Os nomes de domínio personalizados permitem a visualização de objetos no navegador e a entrega acelerada por CDN.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint , por exemplo,ap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the bucket's region.
cfg.region = '<region-id>'
# Specify your custom domain name. For example, www.example-***.com.
cfg.endpoint = 'https://www.example-***.com'
# Set use_cname to True to use a custom domain name.
cfg.use_cname = True
# Create an OSS client.
client = oss.Client(cfg)
# Use the client for subsequent operations.
# Script entry point.
if __name__ == "__main__":
main()
Controle de tempo limite
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint , comoap-southeast-1.
import alibabacloud_oss_v2 as oss
from typing import Dict, Any
def main():
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration.
cfg = oss.config.load_default()
# Override the default connection timeout (10 seconds).
cfg.connect_timeout = 30
# Override the default read/write timeout (20 seconds).
cfg.readwrite_timeout = 30
# Set the credentials provider.
cfg.credentials_provider = credentials_provider
# Specify the region.
cfg.region = '<region-id>'
# Create an OSS client with the specified configuration.
client = oss.Client(cfg)
# Run the main function when the script is executed directly.
if __name__ == "__main__":
main()
Política de nova tentativa
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint , por exemplo,ap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
"""
SDK retry policy configuration:
Default retry policy:
If you do not configure a retry policy, the SDK uses StandardRetryer() by default. The default configuration is as follows:
- max_attempts: The maximum number of retry attempts. Default: 3.
- max_backoff: The maximum backoff time in seconds. Default: 20.
- base_delay: The base delay time in seconds. Default: 0.2.
- backoff_delayer: The backoff algorithm. The SDK uses exponential backoff with jitter (FullJitter) by default.
Formula: random.uniform(0, 1) * min(2 ** attempts * base_delay, max_backoff)
- error_retryables: The types of retryable errors. For more information, see https://gosspublic.alicdn.com/sdk-doc/alibabacloud-oss-python-sdk-v2/latest/_modules/alibabacloud_oss_v2/retry/error_retryable.html
When a retryable error occurs, the client delays and retries the request according to this configuration.
The overall request latency increases with each retry. If the default configuration does not meet your requirements,
you can customize the retry parameters or modify the retry implementation.
"""
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations.
cfg = oss.config.load_default()
# Retry policy configuration examples:
# 1. Customize the maximum number of retries (default: 3, set to 5 here).
cfg.retryer = oss.retry.StandardRetryer(max_attempts=5)
# 2. Customize the backoff delay time.
# Adjust base_delay to 0.5 seconds (default: 0.2) and max_backoff to 25 seconds (default: 20).
# cfg.retryer = oss.retry.StandardRetryer(max_backoff=25, base_delay=0.5)
# 3. Customize the backoff algorithm.
# Replace the default FullJitter algorithm with a fixed-delay backoff of 2 seconds.
# cfg.retryer = oss.retry.StandardRetryer(backoff_delayer=oss.retry.FixedDelayBackoff(2))
# 4. Disable the retry policy.
# Use retry.NopRetryer() to disable all retry attempts.
# cfg.retryer = oss.retry.NopRetryer()
# Set the credentials provider.
cfg.credentials_provider = credentials_provider
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Use the created client for subsequent operations...
# When this script is run directly, call the main function.
if __name__ == "__main__":
main()
Definir o tamanho do pool de conexões
Para o http_client, use o parâmetro max_connections para definir o tamanho do pool de conexões.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região real, por exemplo,ap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# OSS Python SDK V2 connection pool configuration example
import alibabacloud_oss_v2 as oss
def main():
# Load access credentials from environment variables (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET must be set).
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configuration and set the credentials provider.
config = oss.config.load_default()
config.credentials_provider = credentials_provider
# Set the OSS service region.
config.region = "<region-id>"
# ============ Custom HTTP client configuration ============
# Create a dictionary for the HTTP client configuration.
http_client_config = {}
# Set the connection pool size to 100. The default is 20.
http_client_config["max_connections"] = 100
# Create an HTTP client with the custom configuration.
http_client = oss.transport.RequestsHttpClient(**http_client_config)
# Set the custom HTTP client in the configuration object.
config.http_client = http_client
# ============================================
# Initialize the OSS client instance.
client = oss.Client(config)
# Configure bucket and object information.
bucket = "example-bucket" # bucket name
key = "dest.jpg" # object key in OSS
file_path = "dest.jpg" # Local save path
# Download the object from OSS to the specified local path.
client.get_object_to_file(oss.GetObjectRequest(bucket, key), file_path)
print(f"Object download complete: {key} -> {file_path}")
print(f"Connection pool size set to: {http_client_config['max_connections']}")
if __name__ == "__main__":
# Program entry point
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
HTTP/HTTPS
Use cfg.disable_ssl = True para desativar solicitações HTTPS.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint , como ouap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configuration and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the client region.
cfg.region = '<region-id>'
# Disable HTTPS requests.
cfg.disable_ssl = True
# Create an OSS client using the specified configuration.
client = oss.Client(cfg)
# Use the created client to perform subsequent operations...
# The following entry point calls the main function when the script is run directly.
if __name__ == "__main__":
main()
Servidor proxy
Configure um servidor proxy quando as políticas corporativas restringirem o acesso direto à internet.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint válida, por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
# Set the user agent.
cfg.user_agent = 'aliyun-sdk-python'
# Set the proxy server.
cfg.proxy_host = 'http://user:passswd@proxy.example-***.com'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Use the created client to perform subsequent operations...
# When this script is run directly, call the main function.
if __name__ == "__main__":
main()
Usar um endpoint interno
Acesse recursos do OSS na mesma região por meio de um endpoint interno para reduzir custos e latência.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pelos valores reais de região e endpoint , comoap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configuration and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify the region and set use_internal_endpoint to true.
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
cfg.use_internal_endpoint = True
# # Method 2: Specify the region and endpoint directly.
# # Specify the region where the bucket is located.
# cfg.region = '<region-id>'
# # Specify the internal endpoint for the bucket's region.
# cfg.endpoint = '<endpoint>'
# Create the OSS client.
client = oss.Client(cfg)
# Use the client for subsequent operations...
# Call the main function if the script is executed directly.
if __name__ == "__main__":
main()
Aceleração de transferência
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint , por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify the region and set use_accelerate_endpoint to true.
# Specify the bucket's region.
cfg.region = '<region-id>'
cfg.use_accelerate_endpoint = True
# # Method 2: Directly specify the region and the acceleration endpoint.
# # Specify the bucket's region.
# cfg.region = '<region-id>'
# # Specify the acceleration endpoint.
# cfg.endpoint = 'https://oss-accelerate.aliyuncs.com'
# Create an OSS client with the configuration.
client = oss.Client(cfg)
# Use this client for subsequent operations...
# Run the main function if the script is executed directly.
if __name__ == "__main__":
main()
Usar um domínio dedicado
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint , comoap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Load credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default SDK configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
# Specify your dedicated domain. For example, https://service.corp.example.com.
cfg.endpoint = 'https://service.corp.example.com'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Use the created client to perform subsequent operations...
# When this script is run directly, call the main function.
if __name__ == "__main__":
main()
Cliente HTTP personalizado
Substitua o cliente HTTP padrão por cfg.http_client quando os parâmetros de configuração padrão forem insuficientes.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint válida, por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
from typing import Dict, Any
def main():
# Load credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration.
cfg = oss.config.load_default()
# Set the parameters for the HTTP client.
kwargs: Dict[str, Any] = {}
# Set the session.
# kwargs["session"] = requests.Session()
# Set the adapter.
# kwargs["adapter"] = HTTPAdapter()
# Specifies whether to skip certificate verification. Default: false.
# kwargs["insecure_skip_verify"] = False
# Specifies whether to enable HTTP redirection. Default: false.
# kwargs["enabled_redirect"] = False
# Set the proxy server.
# kwargs["proxy_host"] = config.proxy_host
# Set the block size.
# kwargs["block_size"] = 16 * 1024
# Connection timeout in seconds. Default: 10.
kwargs["connect_timeout"] = 30
# Read-write timeout in seconds. Default: 20.
kwargs["readwrite_timeout"] = 30
# Maximum connections. Default: 20.
kwargs["max_connections"] = 1024
# Create an HTTP client with the specified parameters.
cfg.http_client = oss.transport.RequestsHttpClient(**kwargs)
# Set the credentials provider.
cfg.credentials_provider = credentials_provider
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
# Create an OSS client with the specified configuration.
client = oss.Client(cfg)
# Use the client for subsequent OSS operations...
# Calls the main function when the script is executed directly.
if __name__ == "__main__":
main()
Configuração de credenciais de acesso
Escolha um método de credencial adequado ao seu caso de uso.
Usar o AccessKey de um usuário RAM
Inicialize o provedor de credenciais com um par de AccessKey (AccessKey ID e AccessKey Secret) da sua conta Alibaba Cloud ou de um usuário RAM. Este método requer gerenciamento manual de chaves e apresenta maior risco de segurança.
Uma conta Alibaba Cloud tem permissões totais sobre seus recursos. Um par de AccessKey vazado representa uma ameaça significativa à segurança do seu sistema. Recomendamos fortemente que você não use o par de AccessKey de uma conta Alibaba Cloud. Em vez disso, utilize o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.
Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret são exibidos apenas no momento da criação. Salve-os imediatamente em um local seguro. Se você os perder, não será possível recuperá-los e será necessário criar um novo par de AccessKey.
Variáveis de ambiente
-
Use o par de AccessKey de um usuário RAM para configurar as variáveis de ambiente.
Após atualizar as variáveis de ambiente do sistema, reinicie ou atualize seu ambiente de compilação e execução, incluindo IDE, interface de linha de comando, outros aplicativos de desktop e serviços em segundo plano, para carregar as variáveis de ambiente mais recentes.
-
Use variáveis de ambiente para passar as credenciais.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint , por exemplo, ouap-southeast-1.import alibabacloud_oss_v2 as oss def main(): # Load credentials from environment variables for authentication. credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Load the default SDK configurations and set the credential provider. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = '<region-id>' # Create an OSS client with the specified configurations. client = oss.Client(cfg) # Use the created client to perform subsequent operations... # When this script is run directly, call the main function. if __name__ == "__main__": main() # Script entry point. Calls the main function when the file is run directly.
Credenciais estáticas
Codifique rigidamente um par de AccessKey para testes (não para produção):
Não incorpore credenciais diretamente no seu aplicativo em ambientes de produção. Este método destina-se apenas a fins de teste.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint , por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Create a static credential provider and explicitly set the AccessKey ID and AccessKey secret.
# Replace the placeholders with the AccessKey ID and AccessKey secret of your RAM user.
credentials_provider = oss.credentials.StaticCredentialsProvider(
access_key_id="RAM AccessKey ID",
access_key_secret="RAM AccessKey Secret"
)
# Load the default SDK configurations and set the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region where the bucket is located.
cfg.region = '<region-id>'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Use the created client to perform subsequent operations...
# When this script is run directly, call the main function.
if __name__ == "__main__":
main() # Script entry point. Calls the main function when the file is run directly.
Usar credenciais temporárias do STS
Inicialize o provedor de credenciais com credenciais temporárias do STS (AccessKey ID, AccessKey Secret e Security Token). Os tokens devem ser atualizados manualmente antes da expiração.
Para obter credenciais de identidade temporárias chamando a API
AssumeRole, consulte AssumeRole - Obter uma credencial de identidade temporária para uma função RAM.Para obter credenciais de identidade temporárias usando um SDK, consulte Usar um token STS para acessar o OSS.
Ao gerar um token STS, você deve especificar um tempo de expiração. O token torna-se inválido após esse período.
Para obter uma lista de endpoints do STS, consulte Endpoints de serviço.
Variáveis de ambiente
-
Use credenciais de identidade temporárias para definir variáveis de ambiente.
macOS/Linux/Unix
AvisoEssas variáveis de ambiente exigem as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e Security Token) do STS, e não o AccessKey ID e o AccessKey Secret de um usuário RAM.
O AccessKey ID obtido do STS começa com
STS., por exemplo,STS.L4aBSCSJVMuKg5U1****.
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
AvisoEssas variáveis de ambiente exigem as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e Security Token) do STS, e não o AccessKey ID e o AccessKey Secret de um usuário RAM.
O AccessKey ID obtido do STS começa com
STS., por exemplo,STS.L4aBSCSJVMuKg5U1****.
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
Configure o SDK para ler as credenciais das variáveis de ambiente.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint real, por exemplo, ouap-southeast-1.import alibabacloud_oss_v2 as oss def main(): # Load credentials from environment variables. credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Load the default SDK configurations and set the credential provider. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the Bucket is located. cfg.region = '<region-id>' # Create an OSS client with the specified configurations. client = oss.Client(cfg) # Use the created client to perform subsequent operations... # Script entry point if __name__ == "__main__": main() # Calls the main function.
Credenciais estáticas
Codifique rigidamente as credenciais temporárias diretamente (apenas para testes):
Não incorpore credenciais de acesso no seu aplicativo em um ambiente de produção. Este método destina-se apenas a fins de teste.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint real, por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
def main():
# Use the temporary AccessKey ID and AccessKey Secret from STS, not the credentials of your Alibaba Cloud account.
# Note that the AccessKey ID from STS starts with "STS.".
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Provide the Security Token obtained from STS.
sts_security_token = 'yourSecurityToken'
# Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey Secret, and Security Token.
credentials_provider = oss.credentials.StaticCredentialsProvider(
access_key_id=sts_access_key_id,
access_key_secret=sts_access_key_secret,
security_token=sts_security_token,
)
# Load the default SDK configurations and set the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region where the Bucket is located.
cfg.region = '<region-id>'
# Create an OSS client with the specified configurations.
client = oss.Client(cfg)
# Use the created client to perform subsequent operations...
# Script entry point
if __name__ == "__main__":
main() # Calls the main function.
Usar um ARN de função RAM
Inicialize o provedor de credenciais com um ARN de função RAM para acesso delegado (como entre contas). O SDK atualiza automaticamente o token STS via AssumeRole. Use o parâmetro policy para restringir permissões.
Uma conta Alibaba Cloud tem permissões totais sobre seus recursos. Um par de AccessKey vazado representa um risco significativo de segurança para sua conta. Não use o par de AccessKey de uma conta Alibaba Cloud. Utilize um par de AccessKey de um usuário RAM com apenas as permissões mínimas necessárias.
Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret são mostrados apenas uma vez, durante a criação. Você deve salvá-los imediatamente. Se o par de AccessKey for perdido, será necessário criar um novo para substituí-lo.
Para obter um ARN de função RAM, consulte CreateRole - Criar uma função RAM.
-
Adicione a dependência alibabacloud_credentials.
pip install alibabacloud_credentials -
Configure o par de AccessKey e o ARN da função RAM como credenciais de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>pela região e endpoint real, por exemplo, ouap-southeast-1.# -*- coding: utf-8 -*- import os from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config import alibabacloud_oss_v2 as oss def main(): config = Config( # The RAM user's AccessKey ID and AccessKey secret, retrieved from environment variables. access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), type='ram_role_arn', # The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn='<RoleArn>', # The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # Optional. The session duration in seconds. Default: 3600 (1 hour). role_session_expiration=3600 ) cred_client = Client(config) def get_credentials_wrapper(): cred = cred_client.get_credential() return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token) # Create a credential provider to dynamically load credentials. credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper) # Load the default OSS SDK configurations. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = '<region-id>' # Create an OSS client instance. client = oss.Client(cfg) # Use the client for subsequent operations... if __name__ == "__main__": main() # Script entry point. Calls the main function when the file is run directly.
Usar uma função RAM de instância ECS
Para aplicações em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes, use uma função RAM de instância ECS. O SDK atualiza automaticamente o token STS sem credenciais codificadas rigidamente. Criar uma função RAM.
-
Adicione a dependência alibabacloud_credentials.
pip install alibabacloud_credentials -
Configure a função RAM da instância ECS como credencial de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por um ID de região real, por exemplo, ouap-southeast-1.from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config import alibabacloud_oss_v2 as oss def main(): config = Config( type='ecs_ram_role', # Specifies the access credential type. Must be 'ecs_ram_role'. role_name='EcsRoleExample' # Optional: The name of the RAM role granted to the ECS instance. If omitted, the role name is automatically retrieved. We recommend that you set this parameter to reduce requests. ) cred_client = Client(config) def get_credentials_wrapper(): cred = cred_client.get_credential() return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token) # Create a credentials provider to dynamically load credentials. credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper) # Load the default OSS SDK configurations. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = '<region-id>' # Create an OSS client instance. client = oss.Client(cfg) # Use the client for subsequent operations... if __name__ == "__main__": main()
ARN de função OIDC
Para aplicações não confiáveis em nós de trabalho do Container Service for Kubernetes, use RRSA (RAM Roles for Service Accounts) para impor o princípio de menor privilégio no nível do pod. O RRSA monta um arquivo de token OIDC por pod e chama AssumeRoleWithOIDC para trocá-lo por um token STS com escopo definido. Isolar permissões de pods com base no RRSA.
-
Adicione a dependência alibabacloud_credentials.
pip install alibabacloud_credentials
-
Configure o ARN da função OIDC como credencial de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint , por exemplo, ouap-southeast-1.# -*- coding: utf-8 -*- import os from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config import alibabacloud_oss_v2 as oss def main(): config = Config( # Specify the credential type. The value is fixed to 'oidc_role_arn'. type='oidc_role_arn', # The ARN of the RAM role. You can set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn=os.environ.get('<RoleArn>'), # The OIDC provider ARN. You can set this value by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. oidc_provider_arn=os.environ.get('<OidcProviderArn>'), # The OIDC token file path. You can set this value by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'), # The role session name. You can set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # A more restrictive permission policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # The validity period of the role session in seconds. The default is 3600 seconds (1 hour). This parameter is optional. role_session_expiration=3600 ) cred_client = Client(config) def get_credentials_wrapper(): cred = cred_client.get_credential() return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token) # Create a credentials provider to dynamically load credentials. credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper) # Load the default OSS SDK configurations. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = '<region-id>' # Create an OSS client instance. client = oss.Client(cfg) # Use the client for subsequent operations... # Call the main function when this script is run directly. if __name__ == "__main__": main() # Script entry point. Calls the main function when the file is run directly.
Credenciais de acesso personalizadas
Personalize a recuperação de credenciais com uma destas abordagens:
-
Usando a interface
credentials.CredentialsProviderFuncAntes de executar o código de exemplo, substitua o espaço reservado
<region-id>pela região e endpoint real, por exemplo, ouap-southeast-1.import argparse import alibabacloud_oss_v2 as oss import os def main(): def get_credentials_wrapper(): # Return long-term credentials. return oss.credentials.Credentials(access_key_id='access_key_id', access_key_secret='access_key_security') # Return temporary STS credentials. # return oss.credentials.Credentials(access_key_id='access_key_id', access_key_secret='access_key_security', security_token='security_token') credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper) # Load the default SDK configurations and set the credentials provider. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = "<region-id>" # Create an OSS client with the specified configurations. client = oss.Client(cfg) # Use the client to perform subsequent operations... if __name__ == "__main__": main() # Script entry point. Calls the main function when the file is run directly. -
Implementando a interface
credentials.CredentialsProviderAntes de executar o código de exemplo, substitua o espaço reservado
<region-id>pela região e endpoint real, por exemplo, ouap-southeast-1.# -*- coding: utf-8 -*- import alibabacloud_oss_v2 as oss class CredentialProviderWrapper(oss.credentials.CredentialsProvider): def get_credentials(self): # TODO # Customize the logic for obtaining access credentials. # Return long-term credentials: access_key_id, access_key_secret. return oss.credentials.Credentials('<access_key_id>', '<access_key_secret>') # Return temporary STS credentials: access_key_id, access_key_secret, token. # Temporary credentials must be refreshed before they expire. # return oss.credentials.Credentials('<access_key_id>', '<access_key_secret>', '<token>'); def main(): # Instantiate a custom credentials provider. credentials_provider = CredentialProviderWrapper() # Load the default OSS SDK configurations. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Specify the region where the bucket is located. cfg.region = '<region-id>' client = oss.Client(cfg) # Use the client to perform subsequent operations... if __name__ == "__main__": main() # Script entry point. Calls the main function when the file is run directly.
Acesso anônimo
Acesse recursos do OSS com leitura pública sem credenciais.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint real, por exemplo, ouap-southeast-1.
import alibabacloud_oss_v2 as oss
# Create an anonymous credentials provider.
credentials_provider = oss.credentials.AnonymousCredentialsProvider()
# Configure the client.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the bucket's region.
cfg.region = '<region-id>'
# Create an OSS client.
client = oss.Client(cfg)
Solucionar erros
Quando uma solicitação falha, a resposta inclui um código de status HTTP, mensagem, ID da solicitação e código de erro (EC). Use o EC para diagnosticar a causa raiz.
-
Por exemplo, o código a seguir dispara um erro ao tentar baixar um objeto inexistente.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>por uma região e endpoint reais, por exemplo, ouap-southeast-1.import alibabacloud_oss_v2 as oss def main(): # Load credentials from environment variables for authentication. credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Load the default SDK configurations and set the credentials provider. cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider # Set the region in the configuration. cfg.region = '<region-id>' # Create an OSS client with the specified configurations. client = oss.Client(cfg) # Send a request to get the object, specifying the bucket name and object key. result = client.get_object(oss.GetObjectRequest( bucket="Your Bucket Name", # Specify the bucket name. key="Your Object Key", # Specify the object key. )) # Print the status code and request ID from the response. print(f'status code: {result.status_code},' f' request id: {result.request_id},' ) # Use a context manager to ensure the resource is released. with result.body as body_stream: data = body_stream.read() print(f"Object read complete. Data length: {len(data)} bytes") path = "./get-object-sample.txt" with open(path, 'wb') as f: f.write(data) print(f"Object downloaded and saved to: {path}") if __name__ == "__main__": main() # Script entry point. -
A execução do script retorna o seguinte erro. A resposta inclui a linha 'EC': '0026-00000001', que fornece um identificador exclusivo para a causa do erro.
alibabacloud_oss_v2.exceptions.OperationError: operation error GetObject: Error returned by Service. Http Status Code: 404. Error Code: NoSuchKey. Request Id: 67CA9AD3ECB4DB3034E5A92D. Message: The specified key does not exist.. EC: 0026-00000001. Timestamp: 2025-03-07 07:05:55+00:00. Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/asghdjfjdas. -
Para diagnosticar o erro, use o EC da saída de erro e siga estas etapas.
Na caixa de pesquisa, insira o EC, por exemplo, 0026-00000001, e clique em Diagnose.
Revise os resultados da pesquisa para encontrar a causa e a solução do erro. A página de diagnóstico detalha a Problem Description (o objeto alvo não existe) e lista Possible Causes (por exemplo, falha no upload do objeto ou exclusão por um usuário, regra de ciclo de vida ou replicação entre regiões), um Problem Example e uma Solution. A solução pode sugerir o uso da interface
HeadObjectpara verificar se o objeto existe, o uso da interfaceListObjectVersionspara verificar o VersionID, ou a revisão de configurações de convenções de nomenclatura, regras de ciclo de vida, permissões de usuário e replicação entre regiões. A seção References na parte inferior contém links para a documentação sobreNoSuchKeyeNoSuchVersion.
Exemplos de código
Exemplos de código para operações comuns: