2
votes

In my GAE Python app, I'm writing code to store images in GCS.

I write the images as follows:

bucket_name = os.environ.get(u'BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
filename = u'/{}/{}/image'.format(bucket_name, str(object.key.id()))
mimetype = self.request.POST[u'image_file'].type
gcs_file = cloudstorage.open(filename, 'w', content_type=mimetype,
                                    options={'x-goog-acl': 'public-read'})
gcs_file.write(self.request.get(u'image_file'))
gcs_file.close()

The first time I use this code to write a particular filename, I can access that file with its filename:

https://storage.googleapis.com/<app>.appspot.com/<id>/image

And I can also click the name "image" on the GCS Storage Browser and see the image.

Yay! It all seems to work.

But when I upload a different image to the same filename, something confusing happens: when I display the filename in the browser, either via an <img> tag or as the URL in a separate browser tab, the old image appears. Yet when I display "image" via the GCS Storage Browser, it shows the new image.

By the way, as an additional data point, although I specify public-read when I open the file for writing, the "shared publicly" column is blank for that file on the GCS Storage Browser page.

I tried deleting the file before the open statement, even though w is supposed to act as an overwrite, but it didn't make any difference.

Can anyone explain how the filename continues to access the old version of the file, even though the GCS Storage Browser shows the new version, and more importantly, what I need to do to make the filename access the new version?

EDIT:

Continuing to research this problem, I found the following statement at https://cloud.google.com/storage/docs/accesscontrol:

If you need to ensure that updates become visible immediately, you should set
a Cache-Control header of "Cache-Control:private, max-age=0, no-transform" on
such objects.

However, I can't see how to do this using Cloudstorage "open" command or in any other way from my Python program. So if this is the solution, can someone tell me how to set the Cache-Control header for these image files I'm creating?

1

1 Answers

3
votes

Here is an example open setting cache control:

with gcs.open(new_zf.gcs_filename, 'w', content_type=b'multipart/x-zip',
                  options={b'x-goog-acl': b'public-read', b'cache-control': b'private, max-age=0, no-cache'}) as nzf:

taken from this respository