Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga por rangos con OSS SDK for Python 1.0

Última actualización: Sep 22, 2026

Descargue un rango específico de bytes de un objeto en lugar del objeto completo.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

  • Para ejecutar una descarga por rangos, es obligatorio contar con el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Descargar un rango de bytes válido

A continuación se muestra un ejemplo de código para especificar un rango válido y descargar datos:

# -*- 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 un rango no válido para descargar datos

Si un objeto tiene un tamaño de 1,000 bytes, el rango válido va del byte 0 al byte 999. Cuando el rango especificado queda fuera de estos límites, el parámetro no surte efecto. En ese caso, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto. A continuación se muestran ejemplos de solicitudes no válidas y sus resultados:

  • Si establece Range: bytes en 500-2000, el valor final del rango no es válido. Por lo tanto, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto.

  • Si establece Range: bytes en 1000-2000, el valor inicial del rango no es válido. En consecuencia, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto.

Usar el comportamiento estándar de rangos

Si agrega x-oss-range-behavior:standard al encabezado de la solicitud, el comportamiento de descarga cambia cuando el rango especificado queda fuera del rango válido. Considere un objeto de 1,000 bytes:

  • Si establece Range: bytes en 500-2000, el valor final del rango no es válido. En este escenario, OSS devuelve el código de estado HTTP 206 y los datos comprendidos entre el byte 500 y el byte 999.

  • Si establece Range: bytes en 1000-2000, el valor inicial del rango no es válido. Aquí, OSS devuelve el código de estado HTTP 416 y el código de error InvalidRange.

A continuación se muestra un ejemplo de código para especificar comportamientos estándar al descargar datos por rangos:

# -*- 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)  

Referencias

  • Código de ejemplo completo de descarga por rangos en GitHub.

  • Para obtener más información sobre la operación de API que permite ejecutar descargas por rangos, consulte GetObject.