Recomendamos o OSS Python SDK V2, que redesenha a autenticação, as novas tentativas e o tratamento de erros, além de adicionar paginadores, gerenciadores de transferência e interfaces semelhantes a arquivos.
Início rápido
Comece a usar o OSS Python SDK V1 seguindo as etapas abaixo.
Prepare o ambiente
Instale o Python
O OSS Python SDK V1 é compatível com o Python 2,6, 2,7, 3,3, 3,4, 3,5, 3,6, 3,7, 3,8 ou versões posteriores.
Ao instalar o Python SDK em ambiente Windows, certifique-se de que a versão do Visual C++ seja 15,0 ou superior.
Instale o python-devel
O OSS Python SDK V1 utiliza a biblioteca crcmod para somas de verificação CRC. A extensão C requer o cabeçalho Python.h do python-devel. Sem ele, o SDK recorre à validação CRC em Python puro, tornando uploads e downloads significativamente mais lentos.
Windows
No Windows, os arquivos de cabeçalho necessários estão incluídos na instalação padrão do Python. Não é necessário instalar o python-devel separadamente.
macOS
No macOS, os arquivos de cabeçalho necessários estão incluídos na instalação padrão do Python. Não é necessário instalar o python-devel separadamente.
CentOS
Para instalar o python-devel, execute o comando a seguir.
yum install python-devel
RHEL
Para instalar o python-devel, execute o comando a seguir.
yum install python-devel
Fedora
Para instalar o python-devel, execute o comando a seguir.
yum install python-devel
Debian
Para instalar o python-devel, execute o comando a seguir.
apt-get install python-dev
Ubuntu
Para instalar o python-devel, execute o comando a seguir.
apt-get install python-dev
Instale o SDK
Instale o SDK usando um dos métodos a seguir. Utilize a versão mais recente para garantir compatibilidade com os exemplos de código.
Instalação com pip
Instale o pip. O pip vem instalado por padrão com o Python 2.7.9 ou posterior, ou Python 3.4 ou posterior.
-
Para instalar a versão mais recente do SDK, execute o comando a seguir.
pip install oss2
Instalação a partir do código-fonte
-
Baixe a versão mais recente do SDK no GitHub, descompacte o pacote e navegue até o diretório correspondente. Certifique-se de que o diretório contenha o arquivo setup.py.
Para baixar uma versão anterior do OSS Python SDK V1, consulte o Histórico de lançamentos.
-
Para instalar o SDK, execute o comando a seguir.
python setup.py install
Configure as credenciais de acesso
Configure as credenciais de acesso com o par AccessKey de um usuário RAM.
No RAM console, crie um usuário RAM com um Permanent AccessKey Pair. Salve o par AccessKey e conceda a permissão
AliyunOSSFullAccessao usuário.-
Use o par AccessKey do usuário RAM para configurar as variáveis de ambiente.
Linux
-
Execute os comandos a seguir na interface de linha de comando para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Execute o comando a seguir no terminal para visualizar o tipo de shell padrão.
echo $SHELL -
Realize as operações a seguir com base no tipo de shell padrão.
Zsh
-
Execute os comandos a seguir para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.zshrc -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Execute os comandos a seguir para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bash_profile -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Execute os comandos a seguir no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Execute os comandos a seguir 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) -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Inicialize o cliente
A maioria das operações com o OSS Python SDK V1 utiliza as classes oss2.Service e oss2.Bucket.
A classe
oss2.Servicelista buckets. Ela não oferece suporte a acesso por nomes de domínio personalizados.A classe
oss2.Bucketfaz upload, download e exclusão de arquivos, além de configurar diversas definições do bucket.
Devido a uma alteração de política para 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 realizar operações de API de dados em buckets do OSS localizados em regiões da China continental. Os endpoints públicos padrão têm restrições 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, deverá vincular um certificado SSL válido ao seu domínio personalizado. Isso é obrigatório para acesso ao OSS Console, pois o console impõe o uso de HTTPS.
Inicializar uma instância de bucket
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela sua região e endpoint reais, comoap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for initializing a client with OSS Python SDK V1
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket"
# Initialize an OSS Bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# List files in the bucket.
print("=== List files in the bucket ===")
try:
# Use the list_objects method to list files.
result = bucket.list_objects()
# Iterate through the file list and print only the file names.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal files listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More files are available.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Inicializar uma instância de serviço
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela sua região e endpoint reais, comoap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for initializing a Service instance with OSS Python SDK V1
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Initialize an OSS Service instance.
service = oss2.Service(auth, endpoint, region=region)
# List all buckets.
print("=== List all buckets ===")
try:
# Use BucketIterator to list buckets.
buckets = [b.name for b in oss2.BucketIterator(service)]
# Iterate through the bucket list and print only the bucket names.
for bucket in buckets:
print(bucket)
# Print statistics.
print(f"\nTotal buckets listed: {len(buckets)}")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Configuração do cliente
Personalize parâmetros como endpoint, tempo limite e tamanho do pool de conexões ao inicializar o cliente OSS.
Use um nome de domínio interno
Para acessar o OSS por uma rede interna, use o nome de domínio interno como endpoint.
Substitua o espaço reservado<region-id>no código por uma região real, comoap-southeast-1.
endpoint = "oss-<region-id>-internal.aliyuncs.com"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
Use um nome de domínio personalizado
Para usar um nome de domínio personalizado, defina o endpoint como seu domínio e ative is_cname=True.
Mapeie seu nome de domínio personalizado para o bucket antes de usá-lo. Acesse o OSS usando nomes de domínio personalizados .
# Set the custom domain name.
endpoint = "http://example.com"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, is_cname=True, region=region)
Controle de tempo limite
Defina o parâmetro connect_timeout (em segundos) ao inicializar o cliente. Padrão: 60 segundos.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, connect_timeout=30, region=region)
Tamanho do pool de conexões
Ajuste o tamanho do pool de conexões com o parâmetro pool_size do objeto session.
# Set the connection pool size. The default value is 10.
session = oss2.Session(pool_size=20)
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, session=session, region=region)
Versão do TLS
Para especificar uma versão do TLS, crie uma sessão usando um SSLAdapter personalizado.
O Python SDK 2.18.1 e versões posteriores permitem especificar a versão do TLS.
import ssl
from requests.adapters import HTTPAdapter
# Define a custom adapter to specify the TLS version.
class SSLAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **http_client_config):
# Specify TLS 1.2.
http_client_config["ssl_version"] = ssl.PROTOCOL_TLSv1_2
return super(SSLAdapter, self).init_poolmanager(*args, **http_client_config)
# Create a session by using SSLAdapter.
session = oss2.Session(adapter=SSLAdapter())
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, session=session, region=region)
Desative a verificação CRC
Para desativar a verificação de integridade de dados CRC, defina o parâmetro enable_crc=False.
Mantenha o CRC ativado. Desativá-lo impede que o OSS garanta a integridade dos dados durante uploads e downloads.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, enable_crc=False, region=region)
Versão da assinatura
As assinaturas V1 do Alibaba Cloud Object Storage serão descontinuadas conforme o cronograma a seguir. Recomendamos que você atualize para a assinatura V4 o mais rápido possível para garantir que seus serviços não sejam afetados.
A partir de 1º de março de 2025, novos usuários não podem usar a assinatura V1.
A partir de 1º de setembro de 2025, encerraremos o suporte e a manutenção da assinatura V1, e não será possível criar novos buckets que a utilizem.
O exemplo a seguir inicializa um cliente com a assinatura V1. Para inicialização com assinatura V4, consulte Inicializar um cliente.
Antes de executar o código de exemplo, substitua espaços reservados como <endpoint> pela sua região e endpoint reais, como https://oss-ap-southeast-1.aliyuncs.com .
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# OSS Python SDK V1 client initialization sample code
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name)
# List files in the bucket.
print("=== List files in the bucket ===")
try:
# List files by using the list_objects() method.
result = bucket.list_objects()
# Iterate through the object list and print each object's key.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal files listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More files are available.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Program entry point.
try:
main()
except Exception as e:
print(f"An error occurred while running the program: {e}")
raise
Nome de aplicativo personalizado
Defina o parâmetro app_name para adicionar um identificador personalizado ao cabeçalho User-Agent. Padrão: string vazia.
O nome do aplicativo é transmitido como um valor de cabeçalho HTTP e deve estar em conformidade com os padrões HTTP.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, app_name="client_test", region=region)
Códigos de exemplo
O OSS Python SDK V1 fornece exemplos de código para gerenciamento de buckets, operações de objetos, controle de acesso e transferência criptografada. Use-os como referência ou integre-os ao seu aplicativo.
|
Código de exemplo no GitHub |
Código de exemplo na documentação |
|
Compartilhamento de recursos de origem cruzada (CORS) (Python SDK V1) |
|
|
Alterar a classe de armazenamento de um objeto (Python SDK V1) |
|
|
Limitar a taxa de transferência de uma conexão (Python SDK V1) |
|
Consulte informações de endpoint
Consulte informações de endpoint para todas as regiões disponíveis ou para uma região específica, incluindo endpoints públicos (IPv4), internos e de aceleração de transferência.
O Python SDK 2.18.0 e versões posteriores oferecem suporte à consulta de informações de endpoint.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela sua região e endpoint reais, comoap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for querying endpoint information using the OSS Python SDK
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
print("=== Querying endpoint information for all supported regions ===\n")
# Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for the region where your bucket is located.
endpoint = "<endpoint>"
# Specify the region that corresponds to the endpoint. This parameter is required when you use Signature V4.
region = "<region-id>"
# Initialize an OSS Service instance.
service = oss2.Service(auth, endpoint, region=region)
try:
# Query endpoint information for all supported regions.
result = service.describe_regions()
# Iterate through the region information.
for r in result.regions:
print(f"Region: {r.region}")
print(f" Public (IPv4) Endpoint: {r.internet_endpoint}")
print(f" Internal (Classic Network or VPC) Endpoint: {r.internal_endpoint}")
print(f" Transfer Acceleration Endpoint: {r.accelerate_endpoint}")
print("-" * 80)
# Print statistics.
print(f"\nFound endpoint information for {len(result.regions)} regions.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Para consultar informações de endpoint de uma região específica, especifique o ID da região específico do OSS no método describe_regions.
result = service.describe_regions("oss-<region-id>")
Configuração de credenciais
O OSS oferece suporte a vários métodos de inicialização de credenciais. Escolha um com base nos seus requisitos de autenticação.
Você deve usar a versão 0.3.5 ou posterior do alibabacloud-credentials. O uso de uma versão anterior resultará em erro.
AK de usuário RAM
Ideal para ambientes seguros e estáveis que precisam de acesso de longo prazo ao OSS sem rotação frequente de credenciais. Inicialize o provedor de credenciais com a AccessKey (AK) de um usuário RAM. Isso requer manutenção manual da AK, o que introduz riscos de segurança.
Uma conta Alibaba Cloud tem permissões totais sobre todos os recursos. Se sua AK vazar, seu sistema estará em risco. Em vez disso, use a AK de um usuário RAM com as permissões mínimas necessárias.
Para criar uma AK para um usuário RAM, consulte Criar uma AccessKey. A AccessKey ID e a AccessKey Secret são mostradas apenas no momento da criação. Se você as esquecer, crie uma nova.
Variáveis de ambiente
-
Configure as variáveis de ambiente usando a Access Key (AK) de um usuário RAM.
Linux
-
Execute os comandos a seguir na interface de linha de comando para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Execute o comando a seguir no terminal para visualizar o tipo de shell padrão.
echo $SHELL -
Realize as operações a seguir com base no tipo de shell padrão.
Zsh
-
Execute os comandos a seguir para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.zshrc -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Execute os comandos a seguir para anexar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bash_profile -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Execute os comandos a seguir no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Execute os comandos a seguir 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) -
Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Reinicie ou atualize seu IDE, CLI e outros ambientes de execução após modificar as variáveis de ambiente para carregar os novos valores.
-
Use variáveis de ambiente para fornecer credenciais.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.#!/usr/bin/env python3 # -*- coding: utf-8 -*- # OSS Python SDK V1: Sample code for client initialization import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider def main(): # Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Set the OSS service region. region = "<region-id>" # Set the endpoint. endpoint = "<endpoint>" # Set the bucket name. bucket_name = "example-bucket-hz" # Initialize an OSS Bucket instance. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # List objects in the bucket. print("=== List objects in the bucket ===") try: # Use the list_objects method to list objects. result = bucket.list_objects() # Iterate through the object list and print only the object keys. for obj in result.object_list: print(obj.key) # Print statistics. print(f"\nTotal objects listed: {len(result.object_list)}") if result.is_truncated: print("Note: The result is truncated. More objects are not listed.") except oss2.exceptions.OssError as e: print(f"OSS error: {e}") raise except Exception as e: print(f"An error occurred: {e}") raise if __name__ == "__main__": # Entry point of the program. try: main() except Exception as e: print(f"An error occurred during execution: {e}") raise
Credenciais estáticas
O código de exemplo a seguir mostra como codificar credenciais diretamente no seu aplicativo.
Não incorpore credenciais em aplicativos 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 espaços reservados como<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# OSS Python SDK V1: Sample code for client initialization
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Specify the AccessKey ID and AccessKey Secret of a RAM user.
access_key_id = 'yourAccessKeyID'
access_key_secret = 'yourAccessKeySecret'
# Configure access credentials using the Access Key (AK) of the RAM user.
auth = oss2.AuthV4(access_key_id, access_key_secret)
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket-hz"
# Initialize an OSS Bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# List objects in the bucket.
print("=== List objects in the bucket ===")
try:
# Use the list_objects method to list objects.
result = bucket.list_objects()
# Iterate through the object list and print only the object keys.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal objects listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More objects are not listed.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Credenciais temporárias STS
Indicado para aplicativos que precisam de acesso temporário ao OSS. Inicialize o provedor de credenciais com credenciais temporárias (AccessKey ID, AccessKey Secret e token de segurança) do STS. Você deve atualizar o token STS manualmente antes que ele expire.
Para obter credenciais de acesso temporárias chamando uma operação de API, consulte AssumeRole - Obter credenciais de segurança temporárias para uma função RAM.
Para obter credenciais de acesso temporárias usando um SDK, consulte Usar credenciais temporárias fornecidas pelo STS para acessar o OSS.
Ao gerar um token STS, você deve definir um tempo de expiração. Depois que um token expira, ele não pode mais ser usado.
Para obter uma lista de endpoints do STS, consulte Endpoints de serviço.
Variáveis de ambiente
-
Defina variáveis de ambiente usando credenciais de acesso temporárias.
macOS, Linux e Unix
ImportanteUse as credenciais de acesso temporárias (Access Key ID, Access Key Secret e token de segurança) obtidas do STS, não a Access Key (AK) de um usuário RAM.
A Access Key ID obtida do STS começa com "STS.", por exemplo, "STS.****".
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
ImportanteUse as credenciais de acesso temporárias (Access Key ID, Access Key Secret e token de segurança) obtidas do STS, não a Access Key (AK) de um usuário RAM.
A Access Key ID obtida do STS começa com "STS.", por exemplo, "STS.****".
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> -
Forneça credenciais usando variáveis de ambiente.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Configure access credentials by using the STS AK, SK, and Security Token from environment variables. # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Credenciais estáticas
Você pode codificar credenciais diretamente no seu aplicativo e definir explicitamente as chaves de acesso temporárias.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
# Specify the temporary AccessKey ID and AccessKey Secret obtained from STS, not the AccessKey ID and AccessKey Secret of your Alibaba Cloud account.
# Note that the Access Key ID obtained from STS starts with "STS."
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Specify the security token obtained from STS.
security_token = 'yourSecurityToken'
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the StsAuth instance. Note that setting auth_version to "v4" enables OSS V4 signatures.
auth = oss2.StsAuth(sts_access_key_id,
sts_access_key_secret,
security_token,
auth_version="v4")
# Initialize the bucket using the StsAuth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
ARN de função RAM
Recomendado para acesso entre contas. Inicialize o provedor de credenciais com um ARN de função RAM. A ferramenta de credenciais atualiza automaticamente o token STS chamando AssumeRole antes que ele expire. Você pode definir o parâmetro policy para restringir ainda mais as permissões.
Uma conta Alibaba Cloud tem permissões totais sobre todos os recursos. Se sua AK vazar, seu sistema estará em risco. Em vez disso, use a AK de um usuário RAM com as permissões mínimas necessárias.
Para criar uma AK para um usuário RAM, consulte Criar uma AccessKey. A AccessKey ID e a AccessKey Secret são mostradas apenas no momento da criação. Se você as esquecer, crie uma nova.
Para obter um ARN de função RAM, consulte Criar uma função RAM.
-
Adicione a dependência de credenciais.
pip install alibabacloud_credentials -
Configure a Access Key (AK) e o ARN da função RAM como credenciais de acesso.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Obtain the Access Key (AccessKey ID and AccessKey Secret) of the RAM user 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 the RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn='<RoleArn>', # The role session name. You can set the RoleSessionName 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 validity period of the role session. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Função RAM de instância ECS
Projetado para aplicativos em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes (ACK). Uma função RAM de instância ECS permite a atualização automática do token STS em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes (ACK) sem fornecer uma AK ou token STS. Para obter uma função, consulte Criar uma função RAM. Para anexá-la a uma instância, consulte Função RAM de instância.
-
Adicione a dependência de credenciais.
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 espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='ecs_ram_role', # Credential type. Fixed value: ecs_ram_role. role_name='<RoleName>' # The name of the RAM role attached to the ECS instance. Optional. If not set, it is retrieved automatically. We strongly recommend setting this parameter to reduce requests. ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
ARN de função OIDC
Quando aplicativos não confiáveis são executados em nós de trabalho do ACK, use RRSA para impedir que eles obtenham o token STS da função RAM da instância do nó. O cluster monta um arquivo de token OIDC de conta de serviço por pod e injeta a configuração nas variáveis de ambiente. A ferramenta de credenciais troca o token OIDC por um token STS via AssumeRoleWithOIDC, sem exigir uma AK ou token STS. Configure permissões RAM para uma ServiceAccount para implementar isolamento de permissões de pod usando RRSA.
-
Adicione a dependência de credenciais.
pip install alibabacloud_credentials -
Configure a função OIDC como credencial de acesso.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Credential type. Fixed value: oidc_role_arn. type='oidc_role_arn', # The ARN of the RAM role. You can set the RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn=os.environ.get('<RoleArn>'), # The ARN of the OIDC provider. You can set the OidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. oidc_provider_arn=os.environ.get('<OidcProviderArn>'), # The OIDC token file path. You can set the OidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'), # The role session name. You can set the RoleSessionName 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>', # The validity period of the session. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Contexto do Function Compute
Mais indicado para funções executadas no FC. O FC assume uma função de serviço para obter um token STS (válido por 36 horas) e o passa através do parâmetro Credentials do contexto. Como o tempo máximo de execução da função é de 24 horas, o token não expira durante a execução, portanto, nenhuma atualização é necessária. Para conceder permissões ao FC para acessar o OSS, consulte Usar uma função de função para conceder permissões ao Function Compute para acessar outros serviços de nuvem.
Inicialize o provedor de credenciais com credenciais do contexto do FC.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials
def handler(event, context):
class CredentialProviderWrapper(CredentialsProvider):
def get_credentials(self):
creds = context.credentials
return Credentials(creds.access_key_id, creds.access_key_secret, creds.security_token)
credentials_provider = CredentialProviderWrapper()
# Note that ProviderAuthV4 indicates the use of V4 signatures.
auth = oss2.ProviderAuthV4(credentials_provider)
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
return 'success'
URI de credenciais
Utilize este método para aplicativos que obtêm credenciais de um sistema externo. A ferramenta de credenciais recupera um token STS do URI fornecido e lida com a atualização automática.
Um URI de credenciais é o endereço do servidor de onde obter o token STS.
O serviço de back-end que fornece a resposta do URI de credenciais deve implementar lógica de atualização automática do token STS para garantir que o aplicativo sempre obtenha credenciais válidas.
-
Para garantir que a ferramenta de credenciais possa analisar e usar corretamente o token STS, a resposta do URI deve aderir ao seguinte protocolo:
Código de status da resposta: 200
-
Estrutura do corpo da resposta:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
-
Adicione a dependência de credenciais.
pip install alibabacloud_credentials -
Configure o URI de credenciais como credencial de acesso.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='credentials_uri', # The URI for the credentials, in the format http://local_or_remote_uri/. You can set the CredentialsUri using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. credentials_uri='<CredentialsUri>', ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
AK com rotação automática
Adequado para ambientes onde a AK corre risco de comprometimento. Inicialize o provedor de credenciais com uma ClientKey do KMS, que rotaciona automaticamente a AK do usuário RAM gerenciado. O KMS também suporta rotação imediata se uma AK for comprometida. Para obter uma ClientKey, consulte Criar um ponto de acesso de aplicativo.
-
Adicione a dependência do cliente Secrets Manager.
pip install aliyun-secret-manager-client -
Crie um arquivo de configuração chamado
secretsmanager.properties.# The type of access credential. Fixed value: client_key credentials_type=client_key # The decryption password for the ClientKey. You can read it from an environment variable or a file. Set only one. client_key_password_from_env_variable=<your client key private key password environment variable name> client_key_password_from_file_path=<your client key private key password file path> # The path to the private key file of the ClientKey. client_key_private_key_path=<your client key private key file path> # The region of the associated KMS. cache_client_region_id=[{"regionId":"<regionId>"}] -
Use o arquivo de configuração para fornecer informações de credenciais.
Antes de executar o código de exemplo, substitua espaços reservados como
<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import json import oss2 from oss2 import CredentialsProvider from oss2.credentials import Credentials from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder class CredentialProviderWrapper(CredentialsProvider): def get_credentials(self): secret_cache_client = SecretManagerCacheClientBuilder.new_client() secret_info = secret_cache_client.get_secret_info("<secretName>") secret_value_json = json.loads(secret_info.secret_value) return Credentials(secret_value_json["AccessKeyId"], secret_value_json["AccessKeySecret"]) credentials_provider = CredentialProviderWrapper() # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Provedor de credenciais personalizado
Se nenhum dos métodos de configuração de credenciais acima atender aos seus requisitos, você pode definir um provedor de credenciais personalizado implementando a interface CredentialProvider. Se sua implementação usar um token STS, você também deverá lidar com a atualização das credenciais.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela região e endpoint reais. Por exemplo, substitua<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials
class CredentialProviderWrapper(CredentialsProvider):
def get_credentials(self):
# TODO
# Implement your custom method for obtaining access credentials.
# Return long-term credentials: access_key_id, access_key_secret
return Credentials('<access_key_id>', '<access_key_secrect>')
# Return temporary credentials: access_key_id, access_key_secret, token
# For temporary credentials, you need to refresh them based on their expiration time.
# return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');
credentials_provider = CredentialProviderWrapper()
# Note that ProviderAuthV4 indicates the use of V4 signatures.
auth = oss2.ProviderAuthV4(credentials_provider)
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
Perguntas frequentes
Erro: No module named _crcfunext?
Uploads e downloads usando o OSS Python SDK V1 são mais lentos do que com outras ferramentas, como ossutil ou outros SDKs.
-
Causa:
A biblioteca
_crcfunext.sofalha ao ser gerada durante a compilação docrcmodporque o sistema não possui o arquivoPython.hnecessário. Saiba mais sobre ocrcmodna introdução ao crcmod. -
Solução:
Verifique se o modo de extensão C para
crcmodestá instalado corretamente.-
Execute o comando a seguir para entrar no ambiente Python.
python -
Execute o comando a seguir para importar o módulo de extensão C
_crcfunextdo módulocrcmod.import crcmod._crcfunextO erro a seguir indica que o modo de extensão C para a biblioteca
crcmodfalhou ao instalar.Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named _crcfunext -
Escolha uma solução com base no seu sistema operacional.
Windows
-
Baixe o crcmod-1.7.win32-py2.7.msi ou outra versão do arquivo .msi.
NotaA versão de 32 bits do
crcmodé compatível com sistemas Windows de 32 e 64 bits. Instale o arquivo .msi e, durante o processo de instalação, especifique o caminho de instalação do crcmod para a pasta
Lib\site-packagesno diretório de instalação local do Python. Por exemplo,D:\python\Lib\site-packages\.Após a conclusão da instalação, execute as etapas de verificação do
crcmodnovamente.
Linux
Se esse problema ocorrer em um sistema Linux, realize as etapas a seguir:
-
Execute o comando a seguir para desinstalar o
crcmod.pip uninstall crcmod Instale o
python-devel. Consulte Prepare o ambiente.-
Execute o comando a seguir para reinstalar o
crcmod.pip install crcmodSe a instalação falhar novamente, desinstale o
crcmode execute o comando a seguir para visualizar informações detalhadas de erro.pip install crcmod -v
-
-
Erro: No module named 'Crypto'?
-
Causa:
O módulo
Cryptonão existe no sistema, ou o módulocrypto(com letra inicial minúscula) existe. -
Solução:
Verifique se existe o módulo Crypto no caminho de instalação local do Python, por exemplo,
D:\python3.9\Lib\site-packages.-
Se o módulo Crypto não existir, execute o comando a seguir.
python -m pip install --upgrade setuptools Se existir um módulo chamado
crypto(com c minúsculo), renomeie-o paraCryptoe reinicie o programa.
-
Erro: "não é um comando interno ou externo"?
No Windows, se você receber 'não é reconhecido como um comando interno ou externo', adicione os caminhos de instalação do Python e do pip (geralmente a pasta Scripts no diretório do Python) à variável de ambiente Path. Reinicie o computador para que as alterações entrem em vigor.
Falha na instalação do OSS Python SDK V1
Se a instalação falhar, desinstale e tente novamente.
pip uninstall oss2
Atualize o OSS Python SDK V1
Execute o comando a seguir para atualizar o SDK.
pip install --upgrade oss2
Solucione erros AccessDenied
Um erro AccessDenied indica permissões insuficientes. Solucione o problema da seguinte forma:
Certifique-se de estar usando a AccessKey ID e a AccessKey Secret corretas.
Verifique se o usuário RAM tem as permissões necessárias para as operações de bucket ou objeto.
Verifique a política do bucket: Uma mensagem de erro contendo "Access denied by bucket policy" indica que a solicitação foi bloqueada por uma política de bucket.
Melhore a velocidade de transferência para acesso intrarregional
Para transferências mais rápidas, acesse o OSS a partir de um produto Alibaba Cloud (como ECS) na mesma região do seu bucket, usando um endpoint interno.
Visualize AccessKeys e gerencie AccessKey Secrets
Para visualizar a AccessKey de um usuário RAM: Faça logon no RAM console e selecione o usuário específico para visualizar suas informações de AccessKey.
A AccessKey Secret de um usuário RAM é mostrada apenas no momento da criação. Se você a perder, crie uma nova AccessKey no RAM console. Criar uma AccessKey.