Todos os produtos
Search
Central de documentação

Object Storage Service:OSS Python SDK V2

Última atualização: Jul 02, 2026

GitHub | Guia do desenvolvedor do OSS SDK for Python 2.0 | Documentação do OSS SDK for Python 2.0

Início rápido

image

Pré-requisitos

É necessário ter o Python 3,8 ou superior.

Para verificar sua versão do Python, execute o comando python --version . Se o Python não estiver instalado ou se a versão for inferior a 3,8, baixe e instale o Python .

Instalar o SDK

  • Instale a versão mais recente para garantir que os exemplos de código funcionem corretamente.

    pip install alibabacloud-oss-v2
  • Importe o pacote do SDK:

    import alibabacloud_oss_v2 as oss

Configurar credenciais de acesso

Configure as credenciais com um par de AccessKey de um usuário RAM.

  1. No console do RAM, crie um usuário RAM e selecione Using permanent AccessKey to access. Salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário.

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

    Linux

    1. Anexe as variáveis de ambiente ao arquivo ~/.bashrc.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Aplique as alterações.

        source ~/.bashrc
      2. Verifique as variáveis de ambiente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Verifique o tipo de shell padrão.

      echo $SHELL
      1. Siga as etapas correspondentes ao seu tipo de shell.

        Zsh

        1. Anexe as variáveis de ambiente ao arquivo ~/.zshrc.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Aplique as alterações.

          source ~/.zshrc
        3. Verifique as variáveis de ambiente.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Anexe as variáveis de ambiente ao arquivo ~/.bash_profile.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Aplique as alterações.

          source ~/.bash_profile
        3. Verifique as variáveis de ambiente.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Defina as variáveis de ambiente no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Verifique as variáveis de ambiente.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Defina as variáveis de ambiente no PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Verifique as variáveis de ambiente.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Inicializar o cliente

Importante

Devido a uma alteração de política visando melhorar a conformidade e a segurança, a partir de 20 de março de 2025, novos usuários do OSS devem usar um nome de domínio personalizado (CNAME) para executar operações de API de dados em buckets do OSS localizados em regiões da China continental. Os endpoints públicos padrão estão restritos para essas operações. Consulte o anúncio oficial para obter a lista completa das operações afetadas. Se você acessar seus dados via HTTPS, é obrigatório vincular um certificado SSL válido ao seu domínio personalizado. Isso é obrigatório para acesso pelo OSS Console, pois o console impõe o uso de HTTPS.

Antes de executar o código de exemplo, substitua os espaços reservados, como <region-id> , pelos valores reais de região e endpoint , como ap-southeast-1 .

Sync OSSClient

import alibabacloud_oss_v2 as oss

def main():
    """
    Configuration details for initializing the Python SDK V2 client:

    1. Signature version: The SDK uses Signature V4 by default for enhanced security.
    2. Region configuration: When you initialize the client, you must specify an Alibaba Cloud region ID.
    3. Endpoint configuration:
       - You can use the endpoint parameter to specify a custom endpoint for service requests.
       - If you do not specify an endpoint, the SDK automatically constructs a public endpoint based on the specified region.
    4. Protocol configuration:
       - The SDK uses HTTPS to construct the endpoint by default.
       - To use HTTP, you must explicitly specify the protocol in the endpoint.
    """

    # Load credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Method 1: Specify only the region (Recommended).
    # You must specify a region ID. The SDK automatically constructs an HTTPS endpoint based on the region.
    cfg.region = '<region-id>' 

    # # Method 2: Specify both the region and the endpoint.
    # # You must specify a region ID.
    # cfg.region = '<region-id>'
    # # Specify the public endpoint of the region where the bucket is located.
    # cfg.endpoint = '<endpoint>'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Define the string to upload.
    text_string = "Hello, OSS!"
    data = text_string.encode('utf-8')  # Encode the string as a UTF-8 byte string.

    # Send a request to upload the object. Specify the bucket name, object key, and data.
    result = client.put_object(oss.PutObjectRequest(
        bucket="Your Bucket Name",
        key="Your Object Key",
        body=data,
    ))

    # Print the status code, request ID, and ETag to verify that the request was successful.
    print(f'status code: {result.status_code}\n'
          f'request id: {result.request_id}\n'
          f'etag: {result.etag}'
    )

# When this script is run directly, call the main function.
if __name__ == "__main__":
    main()

Async OSSClient

Requisitos do Async OSSClient:

  • alibabacloud-oss-v2: >= 1.2.0

  • Instalar aiohttp: pip install aiohttp

import asyncio
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.aio as oss_aio

async def main():
    """
    Configuration details for initializing the Python SDK V2 async client:

    1. Signature version: The SDK uses Signature V4 by default for enhanced security.
    2. Region configuration: When you initialize the AsyncClient, you must specify an Alibaba Cloud region ID.
    3. Endpoint configuration:
       - You can use the endpoint parameter to specify a custom endpoint for service requests.
       - If you do not specify an endpoint, the SDK automatically constructs a public endpoint based on the specified region.
    4. Protocol configuration:
       - The SDK uses HTTPS to construct the endpoint by default.
       - To use HTTP, you must explicitly specify the protocol in the endpoint.
    5. Asynchronous features:
       - Import the async module: import alibabacloud_oss_v2.aio as oss_aio
       - Create an async client: oss_aio.AsyncClient(cfg)
       - All operations require the await keyword.
       - You must call await client.close() in a finally block to close the connection.
       - You must install the aiohttp dependency: pip install aiohttp
    """

    # Load credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Method 1: Specify only the region (Recommended).
    # You must specify a region ID. The SDK automatically constructs an HTTPS endpoint based on the region.
    cfg.region = '<region-id>'

    # # Method 2: Specify both the region and the endpoint.
    # # You must specify a region ID.
    # cfg.region = '<region-id>'
    # # Specify the public endpoint of the region where the bucket is located.
    # cfg.endpoint = '<endpoint>'

    # Create an OSS async client with the specified configurations.
    client = oss_aio.AsyncClient(cfg)

    try:
        # Define the string to upload.
        text_string = "Hello, OSS!"
        data = text_string.encode('utf-8')  # Encode the string as a UTF-8 byte string.

        # Send an async request to upload the object. Specify the bucket name, object key, and data.
        # Note: Use the await keyword to wait for the async operation to complete.
        result = await client.put_object(
            oss.PutObjectRequest(
                bucket="Your Bucket Name",
                key="Your Object Key",
                body=data,
            )
        )

        # Print the status code, request ID, and ETag to verify that the request was successful.
        print(f'status code: {result.status_code}\n'
              f'request id: {result.request_id}\n'
              f'etag: {result.etag}'
        )

    except Exception as e:
        print(f'Upload failed: {e}')

    finally:
        # Close the async client connection to prevent resource leaks.
        await client.close()

# When this script is run directly, call the main function.
if __name__ == "__main__":
    # Use asyncio.run() to run the async main function.
    asyncio.run(main())

Saída de upload bem-sucedido:

status code: 200
request id: 6875F95738B0ED3030F086A0
etag: "56AAD346F0899BFE8BDD02C06BBE511E"

Configuração do cliente

Parâmetro

Descrição

Exemplo

region

(Obrigatório) A região para a qual as solicitações são enviadas.

oss.config.Config(region="<region-id>")

credentials_provider

(Obrigatório) O provedor de credenciais de acesso.

oss.config.Config(credentials_provider=provider)

endpoint

O endpoint do serviço. Se não for especificado, o cliente gera automaticamente um endpoint com base na região.

oss.config.Config(endpoint="oss-<region-id>.aliyuncs.com")

http_client

O cliente HTTP. Se não for especificado, o cliente usa um cliente HTTP padrão.

oss.config.Config(http_client=customClient)

retry_max_attempts

O número máximo de tentativas para uma solicitação HTTP com falha. O padrão é 3.

oss.config.Config(retry_max_attempts=5)

retryer

Uma estratégia de nova tentativa personalizada para solicitações HTTP.

oss.config.Config(retryer=customRetryer)

connect_timeout

O tempo limite de conexão em segundos. O padrão é 10.

oss.config.Config(connect_timeout=20)

readwrite_timeout

O tempo limite de leitura/gravação em segundos. O padrão é 20.

oss.config.Config(readwrite_timeout=30)

insecure_skip_verify

Ignora a verificação do certificado SSL. O padrão é false (a verificação é realizada).

oss.config.Config(insecure_skip_verify=true)

enabled_redirect

Ativa o redirecionamento HTTP. O padrão é false.

oss.config.Config(enabled_redirect=true)

proxy_host

O servidor proxy para solicitações.

oss.config.Config(proxy_host="http://user:passswd@proxy.example-***.com")

signature_version

A versão da assinatura a ser usada. O padrão é v4.

oss.config.Config(signature_version="v1")

disable_ssl

Desativa o SSL e usa HTTP. O padrão é false (HTTPS é usado).

oss.config.Config(disable_ssl=true)

use_path_style

Indica se deve usar endereçamento estilo caminho (por exemplo, https://endpoint/bucket-name). O padrão, false, usa endereçamento estilo host virtual (por exemplo, https://bucket-name.endpoint).

oss.config.Config(use_path_style=true)

use_cname

Usa um nome de domínio personalizado para acesso. O padrão é false.

oss.config.Config(use_cname=true)

use_dualstack_endpoint

Usa um endpoint de pilha dupla para acesso. O padrão é false.

oss.config.Config(use_dualstack_endpoint=true)

use_accelerate_endpoint

Usa um endpoint de aceleração para acesso. O padrão é false.

oss.config.Config(use_accelerate_endpoint=true)

use_internal_endpoint

Usa um endpoint interno para acesso. O padrão é false.

oss.config.Config(use_internal_endpoint=true)

disable_upload_crc64_check

Desativa a verificação CRC64 para uploads. O padrão é false (a verificação está ativada).

oss.config.Config(disable_upload_crc64_check=true)

disable_download_crc64_check

Desativa a verificação CRC64 para downloads. O padrão é false (a verificação está ativada).

oss.config.Config(disable_download_crc64_check=true)

additional_headers

Especifica cabeçalhos de solicitação adicionais a serem incluídos na assinatura. Este parâmetro se aplica apenas à versão de assinatura v4.

oss.config.Config(additional_headers=["content-length"])

user_agent

Especifica uma string personalizada para anexar ao cabeçalho User-Agent.

oss.config.Config(user_agent="user identifier")

Nome de domínio personalizado

Os nomes de domínio personalizados permitem a visualização de objetos no navegador e a entrega acelerada por CDN.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela região e endpoint , por exemplo, ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the bucket's region.
    cfg.region = '<region-id>'

    # Specify your custom domain name. For example, www.example-***.com.
    cfg.endpoint = 'https://www.example-***.com'

    # Set use_cname to True to use a custom domain name.
    cfg.use_cname = True

    # Create an OSS client.
    client = oss.Client(cfg)

    # Use the client for subsequent operations.

# Script entry point.
if __name__ == "__main__":
    main()

Controle de tempo limite

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , como ap-southeast-1 .
import alibabacloud_oss_v2 as oss
from typing import Dict, Any

def main():
    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configuration.
    cfg = oss.config.load_default()

    # Override the default connection timeout (10 seconds).
    cfg.connect_timeout = 30

    # Override the default read/write timeout (20 seconds).
    cfg.readwrite_timeout = 30

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region.
    cfg.region = '<region-id>'

    # Create an OSS client with the specified configuration.
    client = oss.Client(cfg)

# Run the main function when the script is executed directly.
if __name__ == "__main__":
    main()

Política de nova tentativa

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela região e endpoint , por exemplo, ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    """
    SDK retry policy configuration:

    Default retry policy:
    If you do not configure a retry policy, the SDK uses StandardRetryer() by default. The default configuration is as follows:
    - max_attempts: The maximum number of retry attempts. Default: 3.
    - max_backoff: The maximum backoff time in seconds. Default: 20.
    - base_delay: The base delay time in seconds. Default: 0.2.
    - backoff_delayer: The backoff algorithm. The SDK uses exponential backoff with jitter (FullJitter) by default.
      Formula: random.uniform(0, 1) * min(2 ** attempts * base_delay, max_backoff)
    - error_retryables: The types of retryable errors. For more information, see https://gosspublic.alicdn.com/sdk-doc/alibabacloud-oss-python-sdk-v2/latest/_modules/alibabacloud_oss_v2/retry/error_retryable.html

    When a retryable error occurs, the client delays and retries the request according to this configuration.
    The overall request latency increases with each retry. If the default configuration does not meet your requirements,
    you can customize the retry parameters or modify the retry implementation.
    """

    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations.
    cfg = oss.config.load_default()

    # Retry policy configuration examples:

    # 1. Customize the maximum number of retries (default: 3, set to 5 here).
    cfg.retryer = oss.retry.StandardRetryer(max_attempts=5)

    # 2. Customize the backoff delay time.
    # Adjust base_delay to 0.5 seconds (default: 0.2) and max_backoff to 25 seconds (default: 20).
    # cfg.retryer = oss.retry.StandardRetryer(max_backoff=25, base_delay=0.5)

    # 3. Customize the backoff algorithm.
    # Replace the default FullJitter algorithm with a fixed-delay backoff of 2 seconds.
    # cfg.retryer = oss.retry.StandardRetryer(backoff_delayer=oss.retry.FixedDelayBackoff(2))

    # 4. Disable the retry policy.
    # Use retry.NopRetryer() to disable all retry attempts.
    # cfg.retryer = oss.retry.NopRetryer()

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Use the created client for subsequent operations...

# When this script is run directly, call the main function.
if __name__ == "__main__":
    main()

Definir o tamanho do pool de conexões

Para o http_client, use o parâmetro max_connections para definir o tamanho do pool de conexões.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região real, por exemplo, ap-southeast-1 .
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# OSS Python SDK V2 connection pool configuration example

import alibabacloud_oss_v2 as oss

def main():

    # Load access credentials from environment variables (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET must be set).
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configuration and set the credentials provider.
    config = oss.config.load_default()
    config.credentials_provider = credentials_provider

    # Set the OSS service region.
    config.region = "<region-id>"

    # ============ Custom HTTP client configuration ============
    # Create a dictionary for the HTTP client configuration.
    http_client_config = {}
    
    # Set the connection pool size to 100. The default is 20.
    http_client_config["max_connections"] = 100
    
    # Create an HTTP client with the custom configuration.
    http_client = oss.transport.RequestsHttpClient(**http_client_config)
    
    # Set the custom HTTP client in the configuration object.
    config.http_client = http_client
    # ============================================
    
    # Initialize the OSS client instance.
    client = oss.Client(config)

    # Configure bucket and object information.
    bucket = "example-bucket"             # bucket name
    key = "dest.jpg"                      # object key in OSS
    file_path = "dest.jpg"                # Local save path

    # Download the object from OSS to the specified local path.
    client.get_object_to_file(oss.GetObjectRequest(bucket, key), file_path)
    print(f"Object download complete: {key} -> {file_path}")
    print(f"Connection pool size set to: {http_client_config['max_connections']}")

if __name__ == "__main__":
    # Program entry point
    try:
        main()
    except Exception as e:
        print(f"An error occurred during execution: {e}")
        raise

HTTP/HTTPS

Use cfg.disable_ssl = True para desativar solicitações HTTPS.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , como ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configuration and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the client region.
    cfg.region = '<region-id>'

    # Disable HTTPS requests.
    cfg.disable_ssl = True

    # Create an OSS client using the specified configuration.
    client = oss.Client(cfg)

    # Use the created client to perform subsequent operations...

# The following entry point calls the main function when the script is run directly.
if __name__ == "__main__":
    main()

Servidor proxy

Configure um servidor proxy quando as políticas corporativas restringirem o acesso direto à internet.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint válida, por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'

    # Set the user agent.
    cfg.user_agent = 'aliyun-sdk-python'

    # Set the proxy server.
    cfg.proxy_host = 'http://user:passswd@proxy.example-***.com'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Use the created client to perform subsequent operations...

# When this script is run directly, call the main function.
if __name__ == "__main__":
    main()

Usar um endpoint interno

Acesse recursos do OSS na mesma região por meio de um endpoint interno para reduzir custos e latência.

Antes de executar o código de exemplo, substitua espaços reservados como <region-id> pelos valores reais de região e endpoint , como ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configuration and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Method 1: Specify the region and set use_internal_endpoint to true.
    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'
    cfg.use_internal_endpoint = True

    # # Method 2: Specify the region and endpoint directly.
    # # Specify the region where the bucket is located.
    # cfg.region = '<region-id>'
    # # Specify the internal endpoint for the bucket's region.
    # cfg.endpoint = '<endpoint>'

    # Create the OSS client.
    client = oss.Client(cfg)

    # Use the client for subsequent operations...

# Call the main function if the script is executed directly.
if __name__ == "__main__":
    main()

Aceleração de transferência

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Method 1: Specify the region and set use_accelerate_endpoint to true.
    # Specify the bucket's region.
    cfg.region = '<region-id>'
    cfg.use_accelerate_endpoint = True

    # # Method 2: Directly specify the region and the acceleration endpoint.
    # # Specify the bucket's region.
    # cfg.region = '<region-id>'
    # # Specify the acceleration endpoint.
    # cfg.endpoint = 'https://oss-accelerate.aliyuncs.com'

    # Create an OSS client with the configuration.
    client = oss.Client(cfg)

    # Use this client for subsequent operations...

# Run the main function if the script is executed directly.
if __name__ == "__main__":
    main()

Usar um domínio dedicado

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela sua região e endpoint , como ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default SDK configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'

    # Specify your dedicated domain. For example, https://service.corp.example.com.
    cfg.endpoint = 'https://service.corp.example.com'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Use the created client to perform subsequent operations...

# When this script is run directly, call the main function.
if __name__ == "__main__":
    main()

Cliente HTTP personalizado

Substitua o cliente HTTP padrão por cfg.http_client quando os parâmetros de configuração padrão forem insuficientes.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint válida, por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss
from typing import Dict, Any

def main():
    # Load credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configuration.
    cfg = oss.config.load_default()

    # Set the parameters for the HTTP client.
    kwargs: Dict[str, Any] = {}

    # Set the session.
    # kwargs["session"] = requests.Session()

    # Set the adapter.
    # kwargs["adapter"] = HTTPAdapter()

    # Specifies whether to skip certificate verification. Default: false.
    # kwargs["insecure_skip_verify"] = False

    # Specifies whether to enable HTTP redirection. Default: false.
    # kwargs["enabled_redirect"] = False

    # Set the proxy server.
    # kwargs["proxy_host"] = config.proxy_host

    # Set the block size.
    # kwargs["block_size"] = 16 * 1024

    # Connection timeout in seconds. Default: 10.
    kwargs["connect_timeout"] = 30

    # Read-write timeout in seconds. Default: 20.
    kwargs["readwrite_timeout"] = 30

    # Maximum connections. Default: 20.
    kwargs["max_connections"] = 1024

    # Create an HTTP client with the specified parameters.
    cfg.http_client = oss.transport.RequestsHttpClient(**kwargs)

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'

    # Create an OSS client with the specified configuration.
    client = oss.Client(cfg)

    # Use the client for subsequent OSS operations...

# Calls the main function when the script is executed directly.
if __name__ == "__main__":
    main()

Configuração de credenciais de acesso

Escolha um método de credencial adequado ao seu caso de uso.

Como escolher uma credencial de acesso

Método de inicialização

Cenários

Pré-requisito

Tipo de credencial

Validade

Método de atualização

Usar o AccessKey de um usuário RAM

Aplicações de longa duração em ambientes seguros sem necessidade de rotação de credenciais.

Sim

AccessKey

Longo prazo

Rotação manual

Usar um token STS

Aplicações em ambientes não confiáveis que exigem acesso temporário e com escopo definido.

Sim

Token STS

Temporário

Atualização manual

Usar um ARN de função RAM

Cenários de acesso delegado, como acesso entre contas.

Sim

Token STS

Temporário

Atualização automática

Usar uma função RAM de instância ECS

Aplicações em computação Alibaba Cloud (ECS, ECI ou nós de trabalho ACK).

Não

Token STS

Temporário

Atualização automática

Usar um ARN de função OIDC

Aplicações não confiáveis em nós de trabalho ACK.

Não

Token STS

Temporário

Atualização automática

Usar uma credencial de acesso personalizada

Recuperação personalizada de credenciais quando os métodos integrados são insuficientes.

Personalizado

Personalizado

Personalizado

Personalizado

Usar o AccessKey de um usuário RAM

Inicialize o provedor de credenciais com um par de AccessKey (AccessKey ID e AccessKey Secret) da sua conta Alibaba Cloud ou de um usuário RAM. Este método requer gerenciamento manual de chaves e apresenta maior risco de segurança.

Aviso
  • Uma conta Alibaba Cloud tem permissões totais sobre seus recursos. Um par de AccessKey vazado representa uma ameaça significativa à segurança do seu sistema. Recomendamos fortemente que você não use o par de AccessKey de uma conta Alibaba Cloud. Em vez disso, utilize o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.

  • Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret são exibidos apenas no momento da criação. Salve-os imediatamente em um local seguro. Se você os perder, não será possível recuperá-los e será necessário criar um novo par de AccessKey.

Variáveis de ambiente

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

  2. Após atualizar as variáveis de ambiente do sistema, reinicie ou atualize seu ambiente de compilação e execução, incluindo IDE, interface de linha de comando, outros aplicativos de desktop e serviços em segundo plano, para carregar as variáveis de ambiente mais recentes.

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

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , por exemplo, ou ap-southeast-1 .
    import alibabacloud_oss_v2 as oss
    
    def main():
        # Load credentials from environment variables for authentication.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Load the default SDK configurations and set the credential provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the bucket is located.
        cfg.region = '<region-id>'
    
        # Create an OSS client with the specified configurations.
        client = oss.Client(cfg)
    
        # Use the created client to perform subsequent operations...
    
    # When this script is run directly, call the main function.
    if __name__ == "__main__":
        main()  # Script entry point. Calls the main function when the file is run directly.

Credenciais estáticas

Codifique rigidamente um par de AccessKey para testes (não para produção):

Aviso

Não incorpore credenciais diretamente no seu aplicativo em ambientes de produção. Este método destina-se apenas a fins de teste.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Create a static credential provider and explicitly set the AccessKey ID and AccessKey secret.
    # Replace the placeholders with the AccessKey ID and AccessKey secret of your RAM user.
    credentials_provider = oss.credentials.StaticCredentialsProvider(
        access_key_id="RAM AccessKey ID",
        access_key_secret="RAM AccessKey Secret"
    )

    # Load the default SDK configurations and set the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region where the bucket is located.
    cfg.region = '<region-id>'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Use the created client to perform subsequent operations...

# When this script is run directly, call the main function.
if __name__ == "__main__":
    main()  # Script entry point. Calls the main function when the file is run directly.

Usar credenciais temporárias do STS

Inicialize o provedor de credenciais com credenciais temporárias do STS (AccessKey ID, AccessKey Secret e Security Token). Os tokens devem ser atualizados manualmente antes da expiração.

Importante

Variáveis de ambiente

  1. Use credenciais de identidade temporárias para definir variáveis de ambiente.

    macOS/Linux/Unix

    Aviso
    • Essas variáveis de ambiente exigem as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e Security Token) do STS, e não o AccessKey ID e o AccessKey Secret de um usuário RAM.

    • O AccessKey ID obtido do STS começa com STS., por exemplo, STS.L4aBSCSJVMuKg5U1****.

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Aviso
    • Essas variáveis de ambiente exigem as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e Security Token) do STS, e não o AccessKey ID e o AccessKey Secret de um usuário RAM.

    • O AccessKey ID obtido do STS começa com STS., por exemplo, STS.L4aBSCSJVMuKg5U1****.

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Configure o SDK para ler as credenciais das variáveis de ambiente.

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint real, por exemplo, ou ap-southeast-1 .
    import alibabacloud_oss_v2 as oss
    
    def main():
        # Load credentials from environment variables.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Load the default SDK configurations and set the credential provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the Bucket is located.
        cfg.region = '<region-id>'
    
        # Create an OSS client with the specified configurations.
        client = oss.Client(cfg)
    
        # Use the created client to perform subsequent operations...
    
    # Script entry point
    if __name__ == "__main__":
        main()  # Calls the main function.

Credenciais estáticas

Codifique rigidamente as credenciais temporárias diretamente (apenas para testes):

Aviso

Não incorpore credenciais de acesso no seu aplicativo em um ambiente de produção. Este método destina-se apenas a fins de teste.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint real, por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

def main():
    # Use the temporary AccessKey ID and AccessKey Secret from STS, not the credentials of your Alibaba Cloud account.
    # Note that the AccessKey ID from STS starts with "STS.".
    sts_access_key_id = 'STS.****************'
    sts_access_key_secret = 'yourAccessKeySecret'
    # Provide the Security Token obtained from STS.
    sts_security_token = 'yourSecurityToken'

    # Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey Secret, and Security Token.
    credentials_provider = oss.credentials.StaticCredentialsProvider(
        access_key_id=sts_access_key_id,
        access_key_secret=sts_access_key_secret,
        security_token=sts_security_token,
    )

    # Load the default SDK configurations and set the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region where the Bucket is located.
    cfg.region = '<region-id>'

    # Create an OSS client with the specified configurations.
    client = oss.Client(cfg)

    # Use the created client to perform subsequent operations...

# Script entry point
if __name__ == "__main__":
    main()  # Calls the main function.

Usar um ARN de função RAM

Inicialize o provedor de credenciais com um ARN de função RAM para acesso delegado (como entre contas). O SDK atualiza automaticamente o token STS via AssumeRole. Use o parâmetro policy para restringir permissões.

Importante
  • Uma conta Alibaba Cloud tem permissões totais sobre seus recursos. Um par de AccessKey vazado representa um risco significativo de segurança para sua conta. Não use o par de AccessKey de uma conta Alibaba Cloud. Utilize um par de AccessKey de um usuário RAM com apenas as permissões mínimas necessárias.

  • Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret são mostrados apenas uma vez, durante a criação. Você deve salvá-los imediatamente. Se o par de AccessKey for perdido, será necessário criar um novo para substituí-lo.

  • Para obter um ARN de função RAM, consulte CreateRole - Criar uma função RAM.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  2. Configure o par de AccessKey e o ARN da função RAM como credenciais de acesso.

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela região e endpoint real, por exemplo, ou ap-southeast-1 .
    # -*- coding: utf-8 -*-
    import os
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    import alibabacloud_oss_v2 as oss
    
    def main():
        config = Config(
            # The RAM user's AccessKey ID and AccessKey secret, retrieved from environment variables.
            access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
            access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
            type='ram_role_arn',
            # The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            role_arn='<RoleArn>',
            # The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            role_session_name='<RoleSessionName>',
            # Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy='<Policy>',
            # Optional. The session duration in seconds. Default: 3600 (1 hour).
            role_session_expiration=3600
        )
    
        cred_client = Client(config)
    
        def get_credentials_wrapper():
            cred = cred_client.get_credential()
            return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token)
    
        # Create a credential provider to dynamically load credentials.
        credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper)
    
        # Load the default OSS SDK configurations.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the bucket is located.
        cfg.region = '<region-id>'
    
        # Create an OSS client instance.
        client = oss.Client(cfg)
    
        # Use the client for subsequent operations...
    
    if __name__ == "__main__":
        main()  # Script entry point. Calls the main function when the file is run directly.

Usar uma função RAM de instância ECS

Para aplicações em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes, use uma função RAM de instância ECS. O SDK atualiza automaticamente o token STS sem credenciais codificadas rigidamente. Criar uma função RAM.

  1. Adicione a dependência alibabacloud_credentials.

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

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por um ID de região real, por exemplo, ou ap-southeast-1 .
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    import alibabacloud_oss_v2 as oss
    
    def main():
        config = Config(
            type='ecs_ram_role',      # Specifies the access credential type. Must be 'ecs_ram_role'.
            role_name='EcsRoleExample'    # Optional: The name of the RAM role granted to the ECS instance. If omitted, the role name is automatically retrieved. We recommend that you set this parameter to reduce requests.
        )
    
        cred_client = Client(config)
    
        def get_credentials_wrapper():
            cred = cred_client.get_credential()
            return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token)
    
        # Create a credentials provider to dynamically load credentials.
        credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper)
    
        # Load the default OSS SDK configurations.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the bucket is located.
        cfg.region = '<region-id>'
    
        # Create an OSS client instance.
        client = oss.Client(cfg)
    
        # Use the client for subsequent operations...
    
    if __name__ == "__main__":
        main()

ARN de função OIDC

Para aplicações não confiáveis em nós de trabalho do Container Service for Kubernetes, use RRSA (RAM Roles for Service Accounts) para impor o princípio de menor privilégio no nível do pod. O RRSA monta um arquivo de token OIDC por pod e chama AssumeRoleWithOIDC para trocá-lo por um token STS com escopo definido. Isolar permissões de pods com base no RRSA.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  1. Configure o ARN da função OIDC como credencial de acesso.

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint , por exemplo, ou ap-southeast-1 .
    # -*- coding: utf-8 -*-
    import os
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    import alibabacloud_oss_v2 as oss
    
    def main():
        config = Config(
            # Specify the credential type. The value is fixed to 'oidc_role_arn'.
            type='oidc_role_arn',
            # The ARN of the RAM role. You can set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            role_arn=os.environ.get('<RoleArn>'),
            # The OIDC provider ARN. You can set this value by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
            oidc_provider_arn=os.environ.get('<OidcProviderArn>'),
            # The OIDC token file path. You can set this value by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
            oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'),
            # The role session name. You can set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            role_session_name='<RoleSessionName>',
            # A more restrictive permission policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy='<Policy>',
            # The validity period of the role session in seconds. The default is 3600 seconds (1 hour). This parameter is optional.
            role_session_expiration=3600
        )
    
        cred_client = Client(config)
    
        def get_credentials_wrapper():
            cred = cred_client.get_credential()
            return oss.credentials.Credentials(access_key_id=cred.access_key_id, access_key_secret=cred.access_key_secret, security_token=cred.security_token)
    
        # Create a credentials provider to dynamically load credentials.
        credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper)
    
        # Load the default OSS SDK configurations.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the bucket is located.
        cfg.region = '<region-id>'
    
        # Create an OSS client instance.
        client = oss.Client(cfg)
    
        # Use the client for subsequent operations...
    
    # Call the main function when this script is run directly.
    if __name__ == "__main__":
        main()  # Script entry point. Calls the main function when the file is run directly.

Credenciais de acesso personalizadas

Personalize a recuperação de credenciais com uma destas abordagens:

  1. Usando a interface credentials.CredentialsProviderFunc

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela região e endpoint real, por exemplo, ou ap-southeast-1 .
    import argparse
    import alibabacloud_oss_v2 as oss
    import os
    
    def main():
    
        def get_credentials_wrapper():
            # Return long-term credentials.
            return oss.credentials.Credentials(access_key_id='access_key_id', access_key_secret='access_key_security')
            # Return temporary STS credentials.
            # return oss.credentials.Credentials(access_key_id='access_key_id', access_key_secret='access_key_security', security_token='security_token')
    
        credentials_provider = oss.credentials.CredentialsProviderFunc(func=get_credentials_wrapper)
    
       # Load the default SDK configurations and set the credentials provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
        
        # Specify the region where the bucket is located.
        cfg.region = "<region-id>"
    
        # Create an OSS client with the specified configurations.
        client = oss.Client(cfg)
    
        # Use the client to perform subsequent operations...
    
    if __name__ == "__main__":
        main()  # Script entry point. Calls the main function when the file is run directly.
  2. Implementando a interface credentials.CredentialsProvider

    Antes de executar o código de exemplo, substitua o espaço reservado <region-id> pela região e endpoint real, por exemplo, ou ap-southeast-1 .
    # -*- coding: utf-8 -*-
    import alibabacloud_oss_v2 as oss
    
    class CredentialProviderWrapper(oss.credentials.CredentialsProvider):
        def get_credentials(self):
            # TODO
            # Customize the logic for obtaining access credentials.
    
            # Return long-term credentials: access_key_id, access_key_secret.
            return oss.credentials.Credentials('<access_key_id>', '<access_key_secret>')
    
            # Return temporary STS credentials: access_key_id, access_key_secret, token.
            # Temporary credentials must be refreshed before they expire.
            # return oss.credentials.Credentials('<access_key_id>', '<access_key_secret>', '<token>');
    
    def main():
        # Instantiate a custom credentials provider.
        credentials_provider = CredentialProviderWrapper()
    
        # Load the default OSS SDK configurations.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Specify the region where the bucket is located.
        cfg.region = '<region-id>'
    
        client = oss.Client(cfg)
    
        # Use the client to perform subsequent operations...
    
    if __name__ == "__main__":
        main()  # Script entry point. Calls the main function when the file is run directly.

Acesso anônimo

Acesse recursos do OSS com leitura pública sem credenciais.

Antes de executar o código de exemplo, substitua o espaço reservado <region-id> por uma região e endpoint real, por exemplo, ou ap-southeast-1 .
import alibabacloud_oss_v2 as oss

# Create an anonymous credentials provider.
credentials_provider = oss.credentials.AnonymousCredentialsProvider()

# Configure the client.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the bucket's region.
cfg.region = '<region-id>'

# Create an OSS client.
client = oss.Client(cfg)

Solucionar erros

Quando uma solicitação falha, a resposta inclui um código de status HTTP, mensagem, ID da solicitação e código de erro (EC). Use o EC para diagnosticar a causa raiz.

  1. Por exemplo, o código a seguir dispara um erro ao tentar baixar um objeto inexistente.

    Antes de executar o código de exemplo, substitua espaços reservados como <region-id> por uma região e endpoint reais, por exemplo, ou ap-southeast-1 .
    import alibabacloud_oss_v2 as oss
    
    def main():
        # Load credentials from environment variables for authentication.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Load the default SDK configurations and set the credentials provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Set the region in the configuration.
        cfg.region = '<region-id>'
    
        # Create an OSS client with the specified configurations.
        client = oss.Client(cfg)
    
        # Send a request to get the object, specifying the bucket name and object key.
        result = client.get_object(oss.GetObjectRequest(
            bucket="Your Bucket Name",  # Specify the bucket name.
            key="Your Object Key",  # Specify the object key.
        ))
    
        # Print the status code and request ID from the response.
        print(f'status code: {result.status_code},'
              f' request id: {result.request_id},'
        )
    
        # Use a context manager to ensure the resource is released.
        with result.body as body_stream:
            data = body_stream.read()
            print(f"Object read complete. Data length: {len(data)} bytes")
    
            path = "./get-object-sample.txt"
            with open(path, 'wb') as f:
                f.write(data)
            print(f"Object downloaded and saved to: {path}")
    
    if __name__ == "__main__":
        main()  # Script entry point.
  2. A execução do script retorna o seguinte erro. A resposta inclui a linha 'EC': '0026-00000001', que fornece um identificador exclusivo para a causa do erro.

    alibabacloud_oss_v2.exceptions.OperationError: operation error GetObject: Error returned by Service.
            Http Status Code: 404.
            Error Code: NoSuchKey.
            Request Id: 67CA9AD3ECB4DB3034E5A92D.
            Message: The specified key does not exist..
            EC: 0026-00000001.
            Timestamp: 2025-03-07 07:05:55+00:00.
            Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/asghdjfjdas.
  3. Para diagnosticar o erro, use o EC da saída de erro e siga estas etapas.

    1. Abra a Plataforma de Diagnóstico Self-service OpenAPI.

    2. Na caixa de pesquisa, insira o EC, por exemplo, 0026-00000001, e clique em Diagnose.

    3. Revise os resultados da pesquisa para encontrar a causa e a solução do erro. A página de diagnóstico detalha a Problem Description (o objeto alvo não existe) e lista Possible Causes (por exemplo, falha no upload do objeto ou exclusão por um usuário, regra de ciclo de vida ou replicação entre regiões), um Problem Example e uma Solution. A solução pode sugerir o uso da interface HeadObject para verificar se o objeto existe, o uso da interface ListObjectVersions para verificar o VersionID, ou a revisão de configurações de convenções de nomenclatura, regras de ciclo de vida, permissões de usuário e replicação entre regiões. A seção References na parte inferior contém links para a documentação sobre NoSuchKey e NoSuchVersion.

Exemplos de código

Exemplos de código para operações comuns:

Descrição

Arquivo de exemplo

Criar um bucket (Python SDK V2)

put_bucket.py

Listar buckets (Python SDK V2)

list_buckets.py

Verificar se um bucket existe (Python SDK V2)

is_bucket_exist.py

Obter a região de um bucket (Python SDK V2)

get_bucket_location.py

Obter informações do bucket (Python SDK V2)

get_bucket_info.py

Obter a capacidade de armazenamento de um bucket (Python SDK V2)

get_bucket_stat.py

Excluir um bucket (Python SDK V2)

delete_bucket.py

Grupos de recursos (Python SDK V2)

Tags de bucket (Python SDK V2)

Requester Pays (Python SDK V2)

Obter informações de endpoint (Python SDK V2)

describe_regions.py

Upload simples (Python SDK V2)

put_object.py

Upload por anexação (Python SDK V2)

append_object.py

Upload multipartido (Python SDK V2)

complete_multipart_upload.py

Upload de formulário (Python SDK V2)

post_object.py

Upload usando URL pré-assinada (Python SDK V2)

presigner_put_object.py

Gerenciador de upload de arquivos (Python SDK V2)

upload_file.py

Download simples (Python SDK V2)

get_object.py

Download por intervalo (Python SDK V2)

get_object.py

Acesso somente leitura tipo arquivo (Python SDK V2)

open_file.py

Download usando URL pré-assinada (Python SDK V2)

presigner_get_object.py

Gerenciador de download de arquivos (Python SDK V2)

download_file.py

Copiar um objeto (Python SDK V2)

copy_object.py

Cópia multipartida (Python SDK V2)

upload_part_copy.py

Gerenciador de cópia de arquivos (Python SDK V2)

copier.py

Verificar se um objeto existe (Python SDK V2)

is_object_exist.py

Listar objetos (Python SDK V2)

list_objects_v2.py

Excluir objetos (Python SDK V2)

Restaurar um objeto (Python SDK V2)

Gerenciar metadados de objeto (Python SDK V2)

Alterar a classe de armazenamento de um objeto (Python SDK V2)

copy_object.py

Renomear um objeto (Python SDK V2)

copy_object.py

Gerenciar links simbólicos (Python SDK V2)

Gerenciar ACLs de bucket (Python SDK V2)

Gerenciar ACLs de objeto (Python SDK V2)

Bucket Policy (Python SDK V2)

put_bucket_policy.py

Gerenciar versionamento (Python SDK V2)

put_bucket_version.py

Proteção contra hotlink (Python SDK V2)

CORS (Python SDK V2)

Política de retenção (Python SDK V2)

Criptografia no lado do servidor (Python SDK V2)

Criptografia no lado do cliente (Python SDK V2)

Replicação (Python SDK V2)

put_bucket_replication.py

Monitoramento de acesso (Python SDK V2)

put_bucket_access_monitor.py

Gerenciamento de ciclo de vida (Python SDK V2)

Inventário de bucket (Python SDK V2)

Logging (Python SDK V2)

Leitura direta de arquivamento (Python SDK V2)

put_bucket_archive_direct_read.py

Recuperação escalar (Python SDK V2)

Índice vetorial (Python SDK V2)

Vincular um nome de domínio personalizado (Python SDK V2)

Aceleração de transferência (Python SDK V2)

put_bucket_transfer_acceleration.py

Processamento síncrono (Python SDK V2)

process_object.py

Processamento assíncrono (Python SDK V2)

async_process_object.py

Bloqueio global de acesso público para OSS (Python SDK V2)

put_public_access_block.py

Bloqueio de acesso público no nível do bucket (Python SDK V2)

put_bucket_public_access_block.py

Bloqueio de acesso público no nível do ponto de acesso (Python SDK V2)

put_access_point_public_access_block.py

Gerenciamento de QoS do pool de recursos (Python SDK V2)

-