This topic describes how to use the simple download method to download an object from a bucket to a local file. This method is straightforward and ideal for quickly downloading files from the cloud to a local device.
Usage notes
The sample code in this topic uses cn-hangzhou, the region ID of China (Hangzhou), as an example. By default, a public Endpoint is used. If you want to access OSS from other Alibaba Cloud products in the same region, use an internal Endpoint. For more information about the regions and Endpoints supported by OSS, see Regions and endpoints.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.
|
API |
Action |
Description |
|
GetObject |
|
Downloads an object. |
|
|
When downloading an object, if you specify the object version through versionId, this permission is required. |
|
|
|
When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required. |
Method definition
get_object(request: GetObjectRequest, **kwargs) → GetObjectResultRequest parameters
Parameter | Type | Description |
request | GetObjectRequest | The request parameters. For more information, see GetObjectRequest |
Return values
Type | Description |
GetObjectResult | The return value. For more information, see GetObjectResult |
For the complete definition of the simple download method, see get_object.
Sample code
You can use the following code to download an object from a bucket to a local file.
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.Scenarios
References
For the complete sample code for simple file downloads, see get_object.py and get_object_to_file.py.