|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2021 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import sys |
| 18 | + |
| 19 | +# [START storage_download_byte_range] |
| 20 | +from google.cloud import storage |
| 21 | + |
| 22 | + |
| 23 | +def download_byte_range( |
| 24 | + bucket_name, source_blob_name, start_byte, end_byte, destination_file_name |
| 25 | +): |
| 26 | + """Downloads a blob from the bucket.""" |
| 27 | + # The ID of your GCS bucket |
| 28 | + # bucket_name = "your-bucket-name" |
| 29 | + |
| 30 | + # The ID of your GCS object |
| 31 | + # source_blob_name = "storage-object-name" |
| 32 | + |
| 33 | + # The starting byte at which to begin the download |
| 34 | + # start_byte = 0 |
| 35 | + |
| 36 | + # The ending byte at which to end the download |
| 37 | + # end_byte = 20 |
| 38 | + |
| 39 | + # The path to which the file should be downloaded |
| 40 | + # destination_file_name = "local/path/to/file" |
| 41 | + |
| 42 | + storage_client = storage.Client() |
| 43 | + |
| 44 | + bucket = storage_client.bucket(bucket_name) |
| 45 | + |
| 46 | + # Construct a client side representation of a blob. |
| 47 | + # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve |
| 48 | + # any content from Google Cloud Storage. As we don't need additional data, |
| 49 | + # using `Bucket.blob` is preferred here. |
| 50 | + blob = bucket.blob(source_blob_name) |
| 51 | + blob.download_to_filename(destination_file_name, start=start_byte, end=end_byte) |
| 52 | + |
| 53 | + print( |
| 54 | + "Downloaded bytes {} to {} of object {} from bucket {} to local file {}.".format( |
| 55 | + start_byte, end_byte, source_blob_name, bucket_name, destination_file_name |
| 56 | + ) |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +# [END storage_download_byte_range] |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + download_byte_range( |
| 64 | + bucket_name=sys.argv[1], |
| 65 | + source_blob_name=sys.argv[2], |
| 66 | + start_byte=sys.argv[3], |
| 67 | + end_byte=sys.argv[4], |
| 68 | + destination_file_name=sys.argv[5], |
| 69 | + ) |
0 commit comments