Todos os produtos
Search
Central de documentação

Object Storage Service:OSS Python SDK V1

Última atualização: Sep 22, 2026

Recomendamos o uso do OSS Python SDK V2, que redesenha a autenticação, o mecanismo de retentativa e o tratamento de erros, além de adicionar paginadores, gerenciadores de transferência e interfaces do tipo arquivo.

Início rápido

Comece a usar o OSS Python SDK V1 seguindo as etapas abaixo.

image

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 um 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 passa a usar a validação CRC em Python puro, o que é significativamente mais lento para uploads e downloads.

Windows

No Windows, os arquivos de cabeçalho necessários já 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 já estão incluídos na instalação padrão do Python. Não é necessário instalar o python-devel separadamente.

CentOS

Para o python-devel, instale o pacote com o seguinte comando.

yum install python-devel

RHEL

Para o python-devel, instale o pacote com o seguinte comando.

yum install python-devel

Fedora

Para o python-devel, instale o pacote com o seguinte comando.

yum install python-devel

Debian

Para o python-devel, instale o pacote com o seguinte comando.

apt-get install python-dev

Ubuntu

Para o python-devel, instale o pacote com o seguinte comando.

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 a compatibilidade com os exemplos de código.

Instale com pip

  1. Instale o pip. O pip vem instalado por padrão com o Python 2.7.9 ou superior, ou Python 3.4 ou superior.

  2. Para a versão mais recente do SDK, instale o pacote com o seguinte comando.

    pip install oss2                   

Instale a partir do código-fonte

  1. A versão mais recente do SDK está no GitHub, ou baixe o pacote diretamente no GitHub, descompacte o pacote e acesse o diretório. 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.

  2. Para o SDK, instale o pacote com o seguinte comando.

    python setup.py install                   

Configure as credenciais de acesso

Agora, configure as credenciais de acesso com o par de AccessKey de um usuário RAM.

  1. No console do RAM, crie um usuário RAM com um Permanent AccessKey Pair. Salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário.

  2. Use o par de AccessKey do usuário RAM para configurar as variáveis de ambiente.

    Linux

    1. Execute os seguintes comandos na interface de linha de comando para adicionar 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
    2. Execute o seguinte comando para aplicar as alterações.

      source ~/.bashrc
    3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o seguinte comando no terminal e visualize o tipo de shell padrão.

      echo $SHELL
    2. Execute as seguintes operações com base no tipo de shell padrão.

      Zsh

      1. Execute os seguintes comandos para adicionar 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
      2. Execute o seguinte comando para aplicar as alterações.

        source ~/.zshrc
      3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Execute os seguintes comandos para adicionar 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
      2. Execute o seguinte comando para aplicar as alterações.

        source ~/.bash_profile
      3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os seguintes comandos no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os seguintes comandos no PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      [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.Service lista buckets. Ela não oferece suporte a acesso por meio de nomes de domínio personalizados.

  • A classe oss2.Bucket realiza o upload, o download e a exclusão de arquivos, além de configurar diversas definições do bucket.

Importante

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 use a custom domain name (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 sã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, precisará bind a valid SSL Certificate para o seu domínio personalizado. Isso é obrigatório para o acesso ao console do OSS, pois o console impõe o uso de HTTPS.

Inicializar uma instância de bucket

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint , como ap-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 service

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint , como ap-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 meio de uma rede interna, use o nome de domínio interno como endpoint.

Substitua o espaço reservado <region-id> no código pelos valores reais de region , como ap-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 para o seu domínio e ative is_cname=True.

Mapeie seu nome de domínio personalizado para o seu bucket antes de usá-lo. Access OSS by Using Custom Domain Names .
# 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.

Importante

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

Importante

As assinaturas V1 do Alibaba Cloud Object Storage serão descontinuadas de acordo com o seguinte cronograma. Recomendamos que você upgrade to V4 signature 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 poderão usar a assinatura V1.

  • A partir de 1º de setembro de 2025, descontinuaremos o suporte e a manutenção da assinatura V1, e você não poderá criar novos buckets que a utilizem.

O exemplo a seguir inicializa um cliente com a assinatura V1. Para a inicialização com a assinatura V4, consulte Initialize a Client.

Antes de executar o código de exemplo, substitua os espaços reservados como <endpoint> pelos valores reais de region and endpoint , 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)

Exemplos de código

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.

Exemplos de código no GitHub

Exemplos de código na documentação

bucket.py

bucket_cname.py

Map a custom domain name (Python SDK V1)

bucket_cors.py

Cross-origin resource sharing (CORS) (Python SDK V1)

bucket_inventory.py

Inventory (Python SDK V1)

bucket_logging.py

Logging (Python SDK V1)

bucket_meta_query.py

Query bucket metadata (Python SDK V1)

bucket_policy.py

Policy

bucket_referer.py

Hotlink protection (Python SDK V1)

bucket_replication.py

Replication (Python SDK V1)

bucket_symlink.py

Manage symbolic links (Python SDK V1)

bucket_tagging.py

Bucket tagging (Python SDK V1)

bucket_transfer_acceleration.py

Transfer acceleration (Python SDK V1)

bucket_versioning.py

Manage versioning (Python SDK V1)

bucket_website.py

Static website hosting

bucket_worm.py

Retention policy

download.py

image.py

Image processing (Python SDK V1)

object_basic.py

object_callback.py

Upload callback (Python SDK V1)

object_check.py

Data integrity check (Python SDK V1)

object_crypto.py

Client-side encryption (Python SDK V1)

object_extra.py

Set user-defined metadata

object_forbid_overwrite.py

Prevent object overwrites (Python SDK V1)

object_operation.py

object_post.py

Post upload

object_progress.py

object_request_payment.py

Requester pays (Python SDK V1)

object_restore.py

Restore an object (Python SDK V1)

server_side_encryption.py

Server-side encryption (Python SDK V1)

object_storage_type.py

Change an object's storage class (Python SDK V1)

sts.py

Access with an STS token (Python SDK V1)

object_tagging.py

select_csv.py

Query an object (Python SDK V1)

traffic_limit.py

Limit the transfer rate of a connection (Python SDK V1)

upload.py

Consultar informações de endpoint

Consulte as informações de endpoint para todas as regiões disponíveis ou uma região específica, incluindo endpoints públicos (IPv4), internos e de aceleração de transferência.

Nota

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 os espaços reservados como <region-id> pelos valores reais de region and endpoint , como ap-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 específico da região 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.

Use a versão 0.3.5 ou posterior do alibabacloud-credentials. O uso de uma versão anterior resultará em erro.

Selecione um tipo de credencial

Método de inicialização

Cenários

Pré-configuração

Tipo de credencial

Validade

Rotação ou atualização

Use the Access Key (AK) of a RAM user

Para aplicativos em ambientes seguros que precisam de acesso de longo prazo aos serviços de cloud sem rotação frequente de credenciais.

Sim

Access Key (AK)

Longo prazo

Rotação manual

Use temporary access credentials from Security Token Service (STS)

Para aplicativos em ambientes não confiáveis que precisam de credenciais com tempo de vida limitado e permissões específicas.

Sim

Token STS

Temporário

Atualização manual

Use a RAM role ARN

Para aplicativos que requerem acesso autorizado aos serviços de cloud, como acesso entre contas.

Sim

Token STS

Temporário

Atualização automática

Use an ECS instance RAM role

Para aplicativos em execução em instâncias do Elastic Compute Service (ECS), instâncias do Elastic Container Instance (ECI) ou nós de trabalho do Container Service for Kubernetes (ACK) da Alibaba Cloud.

Não

Token STS

Temporário

Atualização automática

Use an OIDC role ARN

Para aplicativos não confiáveis em execução em nós de trabalho do Container Service for Kubernetes (ACK) da Alibaba Cloud.

Não

Token STS

Temporário

Atualização automática

Use credentials from the Function Compute (FC) context

Para funções em execução no Function Compute (FC) da Alibaba Cloud.

Não

Token STS

Temporário

Não requer atualização

Use a credentials URI

Para aplicativos que precisam obter credenciais de um sistema externo.

Não

Token STS

Temporário

Atualização automática

Use an auto-rotated Access Key (AK)

Para aplicativos implantados em um ambiente com risco de vazamento de Access Key (AK) e que requerem rotação frequente de credenciais para acesso de longo prazo aos serviços de cloud.

Não

Access Key (AK)

Longo prazo

Rotação automática

Use a custom credential provider

Caso os métodos anteriores não atendam aos seus requisitos, defina um método personalizado para obter credenciais.

Personalizado

Personalizado

Personalizado

Personalizado

AK de usuário RAM

Adequado para ambientes seguros e estáveis que exigem 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. Esse método requer manutenção manual da AK, o que introduz riscos de segurança.

Importante
  • Uma conta Alibaba Cloud tem permissões totais sobre todos os recursos. Se a AK vazar, o sistema ficará em risco. Em vez disso, use a AK de um usuário RAM com as permissões mínimas necessárias.

  • Para a AK de um usuário RAM, crie um novo par consultando Create an AccessKey. O AccessKey ID e o AccessKey Secret são mostrados apenas no momento da criação. Se você os esquecer, crie um novo par.

Variáveis de ambiente

  1. Agora, configure as variáveis de ambiente usando a Access Key (AK) de um usuário RAM.

    Linux

    1. Execute os seguintes comandos na interface de linha de comando para adicionar 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
    2. Execute o seguinte comando para aplicar as alterações.

      source ~/.bashrc
    3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o seguinte comando no terminal e visualize o tipo de shell padrão.

      echo $SHELL
    2. Execute as seguintes operações com base no tipo de shell padrão.

      Zsh

      1. Execute os seguintes comandos para adicionar 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
      2. Execute o seguinte comando para aplicar as alterações.

        source ~/.zshrc
      3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Execute os seguintes comandos para adicionar 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
      2. Execute o seguinte comando para aplicar as alterações.

        source ~/.bash_profile
      3. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os seguintes comandos no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os seguintes comandos no PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Agora, verifique se as variáveis de ambiente estão configuradas com os seguintes comandos.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Reinicie ou atualize seu IDE, CLI e outros ambientes de execução depois de modificar as variáveis de ambiente para carregar os novos valores.

  3. Use variáveis de ambiente para fornecer as credenciais.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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 exemplo de código a seguir mostra como codificar as credenciais diretamente no seu aplicativo.

Importante

Não incorpore credenciais em aplicativos de ambiente de produção. Este método é apenas para fins de teste.

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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 do STS

Adequado para aplicativos que exigem 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. Atualize o token STS manualmente antes que ele expire.

Importante

Variáveis de ambiente

  1. Defina as variáveis de ambiente usando credenciais de acesso temporárias.

    macOS, Linux e Unix

    Importante
    • Use as credenciais de acesso temporárias (Access Key ID, Access Key Secret e token de segurança) obtidas do STS, e não a Access Key (AK) de um usuário RAM.

    • O Access Key ID obtido 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

    Importante
    • Use as credenciais de acesso temporárias (Access Key ID, Access Key Secret e token de segurança) obtidas do STS, e não a Access Key (AK) de um usuário RAM.

    • O Access Key ID obtido 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>
  2. Forneça as credenciais usando variáveis de ambiente.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Codifique as credenciais diretamente no seu aplicativo e defina explicitamente as chaves de acesso temporárias.

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Adequado 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 o AssumeRole antes que ele expire. Defina o parâmetro policy para restringir ainda mais as permissões.

Importante
  • Uma conta Alibaba Cloud tem permissões totais sobre todos os recursos. Se a AK vazar, o sistema ficará em risco. Em vez disso, use a AK de um usuário RAM com as permissões mínimas necessárias.

  • Para a AK de um usuário RAM, crie um novo par consultando Create an AccessKey. O AccessKey ID e o AccessKey Secret são mostrados apenas no momento da criação. Se você os esquecer, crie um novo par.

  • Para obter um ARN de função RAM, consulte Create a RAM role.

  1. Adicione a dependência de credenciais.

    pip install alibabacloud_credentials
  2. Agora, 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 os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Adequado para aplicativos em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes (ACK). A função RAM de instância ECS permite a atualização automática do token STS nesses ambientes sem a necessidade de fornecer uma AK ou token STS. Para obter uma função, consulte Create a RAM role. Para anexá-la a uma instância, consulte Instance RAM role.

  1. Adicione a dependência de credenciais.

    pip install alibabacloud_credentials
  2. Agora, configure a função RAM da instância ECS como a credencial de acesso.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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 o 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. Consulte Configure RAM permissions for a ServiceAccount to implement pod permission isolation by using RRSA.

  1. Adicione a dependência de credenciais.

    pip install alibabacloud_credentials
  2. Agora, configure a função OIDC como a credencial de acesso.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Adequado para funções em execução no FC. O FC assume uma função de serviço para obter um token STS (válido por 36 horas) e o passa por meio 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 Use a function role to grant Function Compute permissions to access other cloud services.

Inicialize o provedor de credenciais com as credenciais do contexto do FC.

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Adequado 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.

Importante
  • Um URI de credenciais é o endereço do servidor do qual o token STS será obtido.

  • O service de backend que fornece a resposta do URI de credenciais deve implementar a lógica de atualização automática do token STS para garantir que o aplicativo sempre obtenha credenciais válidas.

  1. Para garantir que a ferramenta de credenciais possa analisar e usar corretamente o token STS, a resposta do URI deve seguir o 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"
      }
  2. Adicione a dependência de credenciais.

    pip install alibabacloud_credentials
  3. Agora, configure o URI de credenciais como a credencial de acesso.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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 faz a rotação automática da AK gerenciada do usuário RAM. O KMS também oferece suporte à rotação imediata se uma AK for comprometida. Para obter uma ClientKey, consulte Create an Application Access Point.

  1. Adicione a dependência do cliente Secrets Manager.

    pip install aliyun-secret-manager-client
  2. 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>"}]
  3. Use o arquivo de configuração para fornecer as informações da credencial.

    Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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

Caso nenhum dos métodos de configuração de credenciais acima atenda aos seus requisitos, defina um provedor de credenciais personalizado implementando a interface CredentialProvider. Se a sua implementação usar um token STS, também será necessário lidar com a atualização da credencial.

Antes de executar o código de exemplo, substitua os espaços reservados como <region-id> pelos valores reais de region and endpoint . Por exemplo, substitua <region-id> por ap-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?

Os uploads e downloads que usam o OSS Python SDK V1 são mais lentos do que com outras ferramentas, como o ossutil ou outros SDKs.

  • Causa:

    A biblioteca _crcfunext.so não é gerada durante a compilação do crcmod porque o sistema não possui o arquivo Python.h necessário. Saiba mais sobre o crcmod na introdução do crcmod.

  • Solução:

    Agora, verifique se o modo de extensão C para o crcmod está instalado corretamente.

    1. Execute o seguinte comando para entrar no ambiente Python.

      python
    2. Execute o seguinte comando para importar o módulo de extensão C _crcfunext do módulo crcmod.

      import crcmod._crcfunext

      O erro a seguir indica que a instalação do modo de extensão C para a biblioteca crcmod falhou.

      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      ImportError: No module named _crcfunext                                 
    3. Escolha uma solução com base no seu sistema operacional.

      Windows

      1. No Windows, baixe o arquivo crcmod-1.7.win32-py2.7.msi ou outra versão do arquivo .msi.

        Nota

        A versão de 32 bits do crcmod é compatível com sistemas Windows de 32 e 64 bits.

      2. Instale o arquivo .msi e, durante o processo de instalação, especifique o caminho de instalação do crcmod para a pasta Lib\site-packages no diretório de instalação local do Python. Por exemplo, D:\python\Lib\site-packages\.

      3. Após a conclusão da instalação, execute as etapas de verificação do crcmod novamente.

      Linux

      Se esse problema ocorrer em um sistema Linux, execute as seguintes etapas:

      1. Execute o seguinte comando para desinstalar o crcmod.

        pip uninstall crcmod
      2. Instale o python-devel. Consulte Prepare the environment.

      3. Execute o seguinte comando para reinstalar o crcmod.

        pip install crcmod

        Se a instalação falhar novamente, desinstale o crcmod e execute o seguinte comando e visualize informações detalhadas do erro.

        pip install crcmod -v

Erro: No module named 'Crypto'?

  • Causa:

    O módulo Crypto não existe no sistema, ou existe o módulo crypto (com a letra inicial minúscula).

  • Solução:

    Agora, 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 seguinte comando.

      python -m pip install --upgrade setuptools
    • Se existir um módulo chamado crypto (com c minúsculo), renomeie-o para Crypto e reinicie seu programa.

Erro: "não é um comando interno ou externo"?

No Windows, se você receber a mensagem '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 seguinte comando para atualizar o SDK.

 pip install --upgrade oss2

Solucione erros AccessDenied

Um erro AccessDenied indica permissões insuficientes. Solucione o problema da seguinte forma:

  1. Certifique-se de usar o AccessKey ID e o AccessKey Secret corretos.

  2. Agora, verifique se o usuário RAM tem as permissões necessárias para as operações de bucket ou objeto.

  3. Agora, 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 intrarregião

Para transferências mais rápidas, acesse o OSS a partir de um product Alibaba Cloud (como o ECS) na mesma região do seu bucket, usando um endpoint interno.

Visualize AccessKeys e gerencie AccessKey Secrets

  1. Para visualizar a AccessKey de um usuário RAM: acesse o console do RAM e selecione o usuário específico e visualize as informações de AccessKey.

  2. O AccessKey Secret de um usuário RAM é exibido apenas no momento da criação. Se você o perder, crie uma nova AccessKey no console do RAM. Consulte Create an AccessKey.