Este tópico descreve como usar o método de download simples para baixar um objeto de um bucket para um arquivo local. Essa abordagem é direta e ideal para transferir arquivos da cloud para um dispositivo local rapidamente.
Notas de uso
O código de exemplo neste tópico usa cn-hangzhou, o ID da região China (Hangzhou), como referência. Por padrão, o sistema utiliza um endpoint público. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regions and endpoints.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a uma conta Alibaba Cloud não têm permissões inicialmente. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais por meio de RAM policies ou Bucket Policy.
|
API |
Action |
Description |
|
GetObject |
|
Baixa um objeto. |
|
|
Necessária ao baixar um objeto caso você especifique a versão do objeto via versionId. |
|
|
|
Exigida quando os metadados do objeto contêm X-Oss-Server-Side-Encryption: KMS durante o download. |
Definição do método
get_object(request: GetObjectRequest, **kwargs) → GetObjectResult
Parâmetros da solicitação
|
Parâmetro |
Tipo |
Descrição |
|
request |
GetObjectRequest |
Os parâmetros da solicitação. Para obter mais detalhes, consulte GetObjectRequest |
Valores de retorno
|
Tipo |
Descrição |
|
GetObjectResult |
O valor retornado. Para obter mais informações, consulte GetObjectResult |
Para obter a definição completa do método de download simples, consulte get_object.
Código de exemplo
Use o código abaixo para baixar um objeto de um bucket para um arquivo local.
import argparse
import alibabacloud_oss_v2 as oss
import os
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="get object sample")
# Add the --region command-line argument to specify the region in which the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument to specify the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If an endpoint is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configured information to create an OSS client.
client = oss.Client(cfg)
# Execute a request to get the object. Specify the bucket name and object name.
result = client.get_object(oss.GetObjectRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
))
# Print the result of getting the object to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' content range: {result.content_range},'
f' content type: {result.content_type},'
f' etag: {result.etag},'
f' last modified: {result.last_modified},'
f' content md5: {result.content_md5},'
f' cache control: {result.cache_control},'
f' content disposition: {result.content_disposition},'
f' content encoding: {result.content_encoding},'
f' expires: {result.expires},'
f' hash crc64: {result.hash_crc64},'
f' storage class: {result.storage_class},'
f' object type: {result.object_type},'
f' version id: {result.version_id},'
f' tagging count: {result.tagging_count},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' next append position: {result.next_append_position},'
f' expiration: {result.expiration},'
f' restore: {result.restore},'
f' process status: {result.process_status},'
f' delete marker: {result.delete_marker},'
)
# ========== Method 1: Read the entire object ==========
with result.body as body_stream:
data = body_stream.read()
print(f"The file is read. Data length: {len(data)} bytes")
path = "./get-object-sample.txt"
with open(path, 'wb') as f:
f.write(data)
print(f"The file is downloaded and saved to the path: {path}")
# # ========== Method 2: Read in chunks ==========
# with result.body as body_stream:
# chunk_path = "./get-object-sample-chunks.txt"
# total_size = 0
# with open(chunk_path, 'wb') as f:
# # Use a 256 KB block size. You can change the block_size parameter based on your needs.
# for chunk in body_stream.iter_bytes(block_size=256 * 1024):
# f.write(chunk)
# total_size += len(chunk)
# print(f"Data block received: {len(chunk)} bytes | Total: {total_size} bytes")
# print(f"The file is downloaded and saved to the path: {chunk_path}")
# When this script is run directly, the main function is called.
if __name__ == "__main__":
main() # The entry point of the script. When the file is run directly, the main function is called.
Cenários
Download condicional
Exibir barra de progresso no download de arquivos
Download em lote de arquivos para dispositivo local
Referências
Para obter o código completo de exemplos de download simples de arquivos, consulte get_object.py e get_object_to_file.py.