Todos os produtos
Search
Central de documentação

Object Storage Service:Baixe retomável com o OSS SDK for Python 1.0

Última atualização: Jul 03, 2026

O baixe de objetos grandes pode falhar devido a instabilidade na rede ou outras exceções. Em alguns casos, o baixe não é concluído mesmo após várias tentativas. Para resolver esse problema, o Object Storage Service (OSS) oferece o recurso de baixe retomável. Nesse modo, o OSS divide o objeto em várias partes e baixa cada uma separadamente. Após baixar todas as partes, o OSS as combina para formar o objeto completo.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configure credenciais de acesso, consulte Configure credenciais de acesso (Python SDK V1).

  • Este exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.

  • Para utilizar o baixe retomável, você precisa da permissão oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.

Procedimento

Para usar o baixe retomável, siga estas etapas:

  1. Crie um arquivo local temporário cujo nome seja composto pelo nome original do objeto e um sufixo aleatório.

  2. Especifique o cabeçalho Range na solicitação HTTP para ler o objeto por intervalos. Grave o conteúdo lido na posição correspondente do arquivo local temporário.

  3. Após concluir o baixe, renomeie o arquivo temporário para o nome do arquivo de destino. Se o arquivo de destino já existir, os dados baixados substituirão o conteúdo atual; caso contrário, um novo arquivo será criado.

Aviso

Como as informações de checkpoint se sobrescrevem no disco local e nomes de arquivos temporários podem entrar em conflito, não execute múltiplos programas ou threads chamando simultaneamente o método oss2.resumable_download para baixar o mesmo objeto para o mesmo arquivo de destino.

Exemplos

O código abaixo ilustra como execute um baixe retomável:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
# Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
oss2.resumable_download(bucket, 'exampledir/exampleobject.txt', 'D:\\localpath\\examplefile.txt')
# If you do not specify a directory by using the store parameter, the .py-oss-upload directory is created in the HOME directory to store the checkpoint information. 

# You can configure the following optional parameters if you use OSS SDK for Python version 2.1.0 or later. 
# import sys
# # If the length of the data to download cannot be determined, the value of total_bytes is None. 
# def percentage(consumed_bytes, total_bytes):
#     if total_bytes:
#         rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
#         print('\r{0}% '.format(rate), end='')
#         sys.stdout.flush()
# # If you use the store parameter to specify a directory, the checkpoint information is stored in the specified directory. If you use the num_threads parameter to specify the number of concurrent download threads, make sure that the value of oss2.defaults.connection_pool_size is greater than or equal to the number of concurrent download threads. The default number of concurrent threads is 1. 
# oss2.resumable_download(bucket,  'exampledir/exampleobject.txt', 'D:\\localpath\\examplefile.txt',
#                       store=oss2.ResumableDownloadStore(root='/tmp'),
#                       # Specify that resumable download is used when the length of the object is greater than or equal to the value of the multipart_threshold parameter. The multipart_threshold parameter is optional and its default value is 10 MB. 
#                       multiget_threshold=100*1024,
#                       # Specify the size of each part. Unit: bytes. The valid part size ranges from 100 KB to 5 GB. The default part size is 100 KB. 
#                       part_size=100*1024,
#                       # Configure the callback function that you want to use to indicate the progress of the resumable download task. 
#                       progress_callback=percentage,
#                       # If you use num_threads to set the number of concurrent download threads, set oss2.defaults.connection_pool_size to a value that is greater than or equal to the number of concurrent download threads. The default number of concurrent threads is 1. 
#                       num_threads=4)

Referências

  • Para acessar o código completo de exemplo sobre baixe retomável, visite o GitHub.

  • Para mais detalhes sobre a operação de API de baixe retomável, consulte GetObject.