Set metadata in Google Cloud Storage using gcloud-python
Asked Answered
F

3

11

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.

Fluctuant answered 15/10, 2015 at 9:40 Comment(0)
P
16

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
Patois answered 24/10, 2015 at 16:39 Comment(3)
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.Tonus
After setting the metadata as shown here, you must call blob.patch(). Then this works just fine for me.Tory
@JoeRivera maybe by doing blob.content_disposition = 'form-data' solves your problem. By doing it directly against the blob instead using metadata attribute.Chiliad
S
4
blob.content_disposition = "attachment"
blob.patch()
Shu answered 9/10, 2020 at 4:52 Comment(0)
C
0
blob.cache_control = "no-store"
blob.patch()

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

Cuprite answered 26/7, 2022 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.