O download via streaming permite baixar um objeto em incrementos, na forma de fluxos de dados. Esse método é ideal para objetos grandes ou quando o download demanda muito tempo, pois viabiliza a transferência gradual do conteúdo.
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 mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Os exemplos abaixo demonstram como criar uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização.
Para usar o download via streaming, você precisa da permissão
oss:GetObject. Para saber mais, consulte Conceder uma política personalizada.
Código de exemplo
O código a seguir exemplifica como baixar o objeto exampleobject.txt de um bucket chamado examplebucket via streaming:
# -*- 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!")
O exemplo abaixo mostra como salvar os dados do objeto exampleobject.txt, obtidos via streaming, em um arquivo local chamado examplefile.txt no diretório 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)
Este trecho ilustra como copiar o conteúdo do objeto exampleobject.txt, lido via streaming, para um novo objeto denominado 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)