Todos os produtos
Search
Central de documentação

Object Storage Service:Range download using OSS SDK for Python 1.0

Última atualização: Jul 03, 2026

Baixe um intervalo específico de bytes de um objeto em vez do objeto inteiro.

Observações

  • Este tópico utiliza 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 regiões e endpoints do OSS, consulte Regiões e endpoints.

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).

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

  • Para baixar dados por intervalo, você precisa da permissão oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.

Baixar um intervalo de bytes válido

O código de exemplo a seguir mostra como especificar um intervalo válido para baixar dados:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
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)

# If an object is 1,000 bytes in size, the valid range is from byte 0 to byte 999. 
# Query data that is within the range from byte 0 to byte 999, which includes a total of 1,000 bytes. If the specified value range is invalid, the entire object is downloaded. For example, if the start or end of the specified range is a negative number or the specified value is greater than the object size, all content of the object is downloaded. 
object_stream = bucket.get_object('<yourObjectName>', byte_range=(0, 999))

Especificar um intervalo inválido para baixar dados

Para um objeto de 1.000 bytes, o intervalo válido vai do byte 0 ao byte 999. Se o intervalo especificado estiver fora desse limite, ele não terá efeito. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados completos do objeto. Os exemplos a seguir mostram solicitações inválidas e seus respectivos resultados:

  • Se você definir Range: bytes como 500-2000, o valor final do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e todos os dados do objeto.

  • Se você definir Range: bytes como 1000-2000, o valor inicial do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e o conteúdo integral do objeto.

Usar o comportamento padrão de intervalo

Ao adicionar x-oss-range-behavior:standard ao cabeçalho da solicitação, o comportamento de download muda quando o intervalo especificado ultrapassa os limites válidos. Considere um objeto de 1.000 bytes:

  • Se você definir Range: bytes como 500-2000, o valor final excederá o limite. Nesse caso, o OSS retorna o código de status HTTP 206 e apenas os dados entre os bytes 500 e 999.

  • Se você definir Range: bytes como 1000-2000, o valor inicial será inválido. Nesse caso, o OSS retorna o código de status HTTP 416 e o código de erro InvalidRange.

O código de exemplo a seguir mostra como especificar o comportamento padrão para downloads por intervalo:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
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)

# Create an object whose size is 1,000 bytes. 
object_name = 'rangeTest.txt'
content = 'a' * 1000
bucket.put_object(object_name, content)

headers = {'x-oss-range-behavior': 'standard'}

# If the value at the end of the range is invalid, OSS returns the data that is within the range from byte 500 to byte 999 and the HTTP status code 206. 
object_stream = bucket.get_object(object_name, byte_range=(500, 2000), headers=headers)
print('standard get 500~2000 http status code:', object_stream.status)
print('standard get 500~2000 contnet_length:', object_stream.content_length)

try:
    # If the value at the start of the range is invalid, an exception is thrown. Then, OSS returns the HTTP status code 416 and the error code InvalidRange. 
    object_stream = bucket.get_object(object_name, byte_range=(1000, 2000), headers=headers)
except oss2.exceptions.ServerError as e:
    print('standard get 1000~2000 http status code:', e.status)
    print('standard get 1000~2000 error code:', e.code)  

Referências

  • Código completo de exemplo para download por intervalo no GitHub.

  • Para obter mais informações sobre a operação de API usada para download por intervalo, consulte GetObject.