Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 22, 2026

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

Observações

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

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, configure as credenciais de acesso de acordo com Configure access credentials using OSS SDK for Python 1.0.

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

  • Para fazer o download por intervalo, é necessário ter a permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Download de um intervalo de bytes válido

No código de exemplo a seguir, especifique 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))

Especifique um intervalo inválido para baixar dados

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

  • Defina Range: bytes como 500-2000. O valor no final do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

  • Defina Range: bytes como 1000-2000. O valor no início do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

Use o comportamento de intervalo padrão

Ao adicionar x-oss-range-behavior:standard ao cabeçalho da solicitação, o comportamento de download muda quando o intervalo especificado está fora do intervalo válido. Para um objeto de 1.000 bytes:

  • Defina Range: bytes como 500-2000. O valor no final do intervalo é inválido. Nesse caso, o OSS retorna o código de status HTTP 206 e os dados dentro do intervalo do byte 500 ao byte 999.

  • Defina Range: bytes como 1000-2000. O valor no início do intervalo é inválido. Nesse caso, o OSS retorna o código de status HTTP 416 e o código de erro InvalidRange.

No código de exemplo a seguir, especifique comportamentos padrão para baixar dados 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 de exemplo completo de download por intervalo no GitHub.

  • Para mais informações sobre a operação de API que você pode chamar para fazer o download por intervalo, consulte GetObject.