Search code examples
pythongoogle-cloud-platformgoogle-cloud-storagegcloud-python

Change metadata in google-cloud-storage python library


How to change metadata for the main metadata fields of a file in Google Cloud Storage? I want to modify the primary metadata fields, such as content-disposition or content-encoding.

My setup:

google-cloud-storage 2.3.0.
Google Cloud SDK 359.0.0
app-engine-python 1.9.94
app-engine-python-extras 1.9.94
beta 2021.09.24
bq 2.0.71
cloud-datastore-emulator 2.1.0
core 2021.09.24
gsutil 5.2

However, when I follow the instructions provided in the official documentation (https://cloud.google.com/storage/docs/viewing-editing-metadata#storage-set-object-metadata-python), it only appears to affect custom metadata.

def _open_gcs_file_for_write(gcs_blob, mode='w', options=None, content_type=None):
""" Helper function to open a GCS file for writing. """
  headers = {}
  if options or content_type:
    if options:
        headers.update(options)

    if content_type:
        gcs_blob.content_type = content_type

    gcs_blob.metadata = headers
    gcs_blob.patch()


options = {
   'cache-control': 'max-age=3600',
   'content-disposition': 'inline; filename="example.txt',
   'content-encoding': 'gzip'
}

After call _open_gcs_file_for_write, in Google cloud console of bucket storage, I see only changed custom metadata, instead of specific fields:


Solution

  • The editable fixed-key metadata fields for an object are treated as mutable object properties in the Python client library. You can update them using the _patch_property(self, name, value) method defined in _helpers.py. The property names to use are defined in blob.py.

    After making updates, you must persist then by calling patch() on the blob.