Todos los productos
Search
Centro de documentos

Object Storage Service:Descargue por streaming con OSS SDK para Python 1.0

Última actualización: Sep 03, 2026

La descarga por streaming permite descargar un objeto como flujos de datos en incrementos. Si necesita descargar un objeto grande o si la descarga requiere mucho tiempo, utilice este método para obtener el objeto en incrementos.

Notas

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

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

  • Para utilizar la descarga por streaming, debe contar con el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

A continuación código de ejemplo muestra cómo descargar por streaming un objeto llamado exampleobject.txt desde un bucket llamado examplebucket:

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

# Create a server object. 
# 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)

# The value returned by bucket.get_object is a file-like object that can be iterated. 
# Specify the full path of the object. Do not include the bucket name in the full path of the object. 
object_stream = bucket.get_object('exampleobject.txt')
print(object_stream.read())

# You must call the read() operation to read the object from the stream returned by get_object before you can calculate the CRC-64 value of the object. 
if object_stream.client_crc != object_stream.server_crc:
    print("The CRC checksum between client and server is inconsistent!")

A continuación código de ejemplo muestra cómo descargar los datos de un objeto llamado exampleobject.txt desde un flujo hacia un archivo llamado examplefile.txt en el directorio D:\localpath:

import shutil
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Create a server object. 
# 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)

# object_stream is a file-like object. You can use the shutil.copyfileobj method to download the data from a stream to the local file. 
# Specify the full path of the object. Do not include the bucket name in the full path of the object. 
object_stream = bucket.get_object('exampleobject.txt')
# Download the object as a local file in the specified path. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded file is saved in the path. 
# If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
with open('D:\\localpath\\examplefile.txt', 'wb') as local_fileobj:
    shutil.copyfileobj(object_stream, local_fileobj)

A continuación código de ejemplo muestra cómo copiar los datos de un objeto llamado exampleobject.txt desde un flujo hacia un objeto llamado exampleobjectnew.txt:

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Create a server object. 
# 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)

# object_stream is an iterable object. You can copy the data of the object from a stream to another object in the same bucket. 
# Specify the full path of the object. Do not include the bucket name in the full path of the object. 
object_stream = bucket.get_object('exampleobject.txt')
# Specify the full path of the destination object. Do not include the bucket name in the full path of the object. 
bucket.put_object('exampleobjectnew.txt', object_stream)

Referencias

  • Para consultar el código de ejemplo completo para descargar por streaming, visite GitHub.

  • Para obtener más información sobre la operación de API que puede llamar para descargar por streaming, consulte GetObject.