|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2021 Google Inc. All Rights Reserved. |
| 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 sys |
| 19 | + |
| 20 | + |
| 21 | +"""Sample that asynchronously uploads a file to GCS |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +# [START storage_async_upload] |
| 26 | +# This sample can be run by calling `async.run(async_upload_blob('bucket_name'))` |
| 27 | +async def async_upload_blob(bucket_name): |
| 28 | + """Uploads a number of files in parallel to the bucket.""" |
| 29 | + # The ID of your GCS bucket |
| 30 | + # bucket_name = "your-bucket-name" |
| 31 | + import asyncio |
| 32 | + from functools import partial |
| 33 | + from google.cloud import storage |
| 34 | + |
| 35 | + storage_client = storage.Client() |
| 36 | + bucket = storage_client.bucket(bucket_name) |
| 37 | + |
| 38 | + loop = asyncio.get_running_loop() |
| 39 | + |
| 40 | + tasks = [] |
| 41 | + count = 3 |
| 42 | + for x in range(count): |
| 43 | + blob_name = f"async_sample_blob_{x}" |
| 44 | + content = f"Hello world #{x}" |
| 45 | + blob = bucket.blob(blob_name) |
| 46 | + # The first arg, None, tells it to use the default loops executor |
| 47 | + tasks.append(loop.run_in_executor(None, partial(blob.upload_from_string, content))) |
| 48 | + |
| 49 | + # If the method returns a value (such as download_as_string), gather will return the values |
| 50 | + await asyncio.gather(*tasks) |
| 51 | + |
| 52 | + print(f"Uploaded {count} files to bucket {bucket_name}") |
| 53 | + |
| 54 | + |
| 55 | +# [END storage_async_upload] |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + asyncio.run(async_upload_blob( |
| 60 | + bucket_name=sys.argv[1] |
| 61 | + )) |
0 commit comments