Todos os produtos
Search
Central de documentação

Object Storage Service:Download retomável usando o OSS SDK for Python 1.0

Última atualização: Sep 24, 2026

O download de um objeto grande pode falhar se a rede estiver instável ou se ocorrerem outras exceções. Em alguns casos, a falha pode persistir mesmo após várias tentativas. Para resolver esse problema, o Object Storage Service (OSS) oferece o recurso de download retomável. Nesse processo, o OSS divide o objeto em várias partes e baixa cada parte separadamente. Após baixar todas as partes, o OSS as combina em um objeto completo.

Observações

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

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar as credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Initialization.

  • O uso do download retomável requer a permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Procedimento

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

  1. Crie um arquivo local temporário com um nome 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 com base no intervalo. Em seguida, grave o conteúdo lido na posição correspondente do arquivo local temporário.

  3. Depois de concluir o download, renomeie o arquivo temporário para o arquivo de destino. Se o arquivo de destino já existir, os dados baixados substituirão os dados do arquivo existente. Caso contrário, o OSS cria um novo arquivo.

Aviso

Um registro de checkpoint sobrescreve outro no disco local, ou o nome de um arquivo temporário entra em conflito com outro. Portanto, não use vários programas ou threads para chamar o método oss2.resumable_download simultaneamente para baixar o mesmo objeto no mesmo arquivo de destino.

Exemplos

O código de exemplo a seguir mostra como executar um download 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 de exemplo completo de download retomável, visite o GitHub.

  • Para obter detalhes sobre a operação da API de download retomável, consulte GetObject.