|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2025 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 asyncio |
| 18 | +import argparse |
| 19 | + |
| 20 | +"""Sample that asynchronously downloads multiple files from GCS to application's memory. |
| 21 | +""" |
| 22 | + |
| 23 | + |
| 24 | +# [START storage_async_download] |
| 25 | +# This sample can be run by calling `async.run(async_download_blobs('bucket_name', ['file1', 'file2']))` |
| 26 | +async def async_download_blobs(bucket_name, *file_names): |
| 27 | + """Downloads a number of files in parallel from the bucket. |
| 28 | + """ |
| 29 | + # The ID of your GCS bucket. |
| 30 | + # bucket_name = "your-bucket-name" |
| 31 | + |
| 32 | + # The list of files names to download, these files should be present in bucket. |
| 33 | + # file_names = ["myfile1", "myfile2"] |
| 34 | + |
| 35 | + import asyncio |
| 36 | + from google.cloud import storage |
| 37 | + |
| 38 | + storage_client = storage.Client() |
| 39 | + bucket = storage_client.bucket(bucket_name) |
| 40 | + |
| 41 | + loop = asyncio.get_running_loop() |
| 42 | + |
| 43 | + tasks = [] |
| 44 | + for file_name in file_names: |
| 45 | + blob = bucket.blob(file_name) |
| 46 | + # The first arg, None, tells it to use the default loops executor |
| 47 | + tasks.append(loop.run_in_executor(None, blob.download_as_bytes)) |
| 48 | + |
| 49 | + # If the method returns a value (such as download_as_bytes), gather will return the values |
| 50 | + _ = await asyncio.gather(*tasks) |
| 51 | + for file_name in file_names: |
| 52 | + print(f"Downloaded storage object {file_name}") |
| 53 | + |
| 54 | + |
| 55 | +# [END storage_async_download] |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + parser = argparse.ArgumentParser() |
| 60 | + parser.add_argument('-b', '--bucket_name', type=str, dest='bucket_name', help='provide the name of the GCS bucket') |
| 61 | + parser.add_argument( |
| 62 | + '-f', '--file_name', |
| 63 | + action='append', |
| 64 | + type=str, |
| 65 | + dest='file_names', |
| 66 | + help='Example: -f file1.txt or --file_name my_fav.mp4 . It can be used multiple times.' |
| 67 | + ) |
| 68 | + args = parser.parse_args() |
| 69 | + |
| 70 | + asyncio.run(async_download_blobs(args.bucket_name, *args.file_names)) |
0 commit comments