|
| 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 | +"""Sample that uses a batch request. |
| 20 | +This sample is used on this page: |
| 21 | + https://cloud.google.com/storage/docs/batch |
| 22 | +For more information, see README.md. |
| 23 | +""" |
| 24 | + |
| 25 | +# [START storage_batch_request] |
| 26 | + |
| 27 | +from google.cloud import storage |
| 28 | + |
| 29 | + |
| 30 | +def batch_request(bucket_name, prefix=None): |
| 31 | + """Use a batch request to patch a list of objects with the given prefix in a bucket.""" |
| 32 | + # The ID of your GCS bucket |
| 33 | + # bucket_name = "my-bucket" |
| 34 | + # The prefix of the object paths |
| 35 | + # prefix = "directory-prefix/" |
| 36 | + |
| 37 | + client = storage.Client() |
| 38 | + bucket = client.bucket(bucket_name) |
| 39 | + |
| 40 | + # Accumulate in a list the objects with a given prefix. |
| 41 | + blobs_to_patch = [blob for blob in bucket.list_blobs(prefix=prefix)] |
| 42 | + |
| 43 | + # Use a batch context manager to edit metadata in the list of blobs. |
| 44 | + # The batch request is sent out when the context manager closes. |
| 45 | + # No more than 100 calls should be included in a single batch request. |
| 46 | + with client.batch(): |
| 47 | + for blob in blobs_to_patch: |
| 48 | + metadata = {"your-metadata-key": "your-metadata-value"} |
| 49 | + blob.metadata = metadata |
| 50 | + blob.patch() |
| 51 | + |
| 52 | + print( |
| 53 | + f"Batch request edited metadata for all objects with the given prefix in {bucket.name}." |
| 54 | + ) |
| 55 | + |
| 56 | + |
| 57 | +# [END storage_batch_request] |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + batch_request(bucket_name=sys.argv[1], prefix=sys.argv[2]) |
0 commit comments