9

I am trying to upload a file to Google Cloud Storage using gcloud-python and set some custom metadata properties. To try this I have created a simple script.

import os

from gcloud import storage

client = storage.Client('super secret app id')
bucket = client.get_bucket('super secret bucket name')

blob = bucket.get_blob('kirby.png')
blob.metadata = blob.metadata or {}
blob.metadata['Color'] = 'Pink'
with open(os.path.expanduser('~/Pictures/kirby.png'), 'rb') as img_data:        
    blob.upload_from_file(img_data)

I am able to upload the file contents. After uploading the file I am able to manually set metadata from the developer console and retrieve it.

I can't figure out how to upload the metadata programmatically.

bossylobster
  • 9,993
  • 1
  • 42
  • 61
Remco Haszing
  • 7,178
  • 4
  • 40
  • 83

3 Answers3

15

We discussed on the issue tracker and it surfaced a "bug" in the implementation, or at the very least something which catches users off guard.

Accessing metadata via blob.metadata is read-only. Thus when mutating that result via

blob.metadata['Color'] = 'Pink'

it doesn't actually change the metadata stored on blob.

The current "fix" is to just build up

metadata = {'Color': 'Pink'}
blob.metadata = metadata
bossylobster
  • 9,993
  • 1
  • 42
  • 61
  • I am trying to create and upload a blob with the Content-Disposition meta data to attachment. I've tried passing it using the above code, but it doesn't seem to be working. Any help is much appreciated. – Joe Rivera Feb 10 '20 at 15:30
  • 7
    After setting the metadata as shown here, you must call `blob.patch()`. Then this works just fine for me. – Tanner Apr 03 '20 at 14:45
  • 1
    @JoeRivera maybe by doing `blob.content_disposition = 'form-data'` solves your problem. By doing it directly against the `blob` instead using metadata attribute. – vperezb Apr 07 '20 at 19:56
3
blob.content_disposition = "attachment"
blob.patch()
him229
  • 1,284
  • 1
  • 11
  • 21
0
blob.cache_control = "no-store"
blob.patch()

https://cloud.google.com/storage/docs/viewing-editing-metadata#storage-set-object-metadata-python

roliveira
  • 87
  • 1
  • 12