1

CORS configuration for cloud storage bucket is not getting set using python.

I am following the steps given in: http://google-cloud-python.readthedocs.io/en/latest/storage/buckets.html#google.cloud.storage.bucket.Bucket.cors

That is,

>>> policies = bucket.cors
>>> policies.append({'origin': '/foo', ...})
>>> policies[1]['maxAgeSeconds'] = 3600
>>> del policies[0]
>>> bucket.cors = policies
>>> bucket.update()

If I get CORS configuration for the bucket after following the above steps, it is gives an empty list.

Ashley Thomas
  • 77
  • 2
  • 8
  • You probably want to use https://stackoverflow.com/posts/50522689/edit to edit/update your question in include the exact error message you’re getting — that is, whatever error message you’re seeing in the browser devtools console when you try to send XHR requests to that bucket from your frontend JavaScript code – sideshowbarker May 25 '18 at 06:44
  • I am not getting any error. When I again get CORS configuration for that same bucket, it is empty. That is, cors is not getting set even after bucket.update(). – Ashley Thomas May 25 '18 at 06:51
  • It is difficult to understand what's going on. Add some "print" functions between the lines in your code to see what are you getting in each step, please. You could try also to follow [this CORS troubleshooting documentation](https://cloud.google.com/storage/docs/configuring-cors#troubleshooting), if you didn't already. – Rubén C. May 25 '18 at 09:39

1 Answers1

3

bucket.cors is a sequence mapping of each CORS policy.

Since you're not sharing exactly how you're updating your CORS entries, I assume that you're passing a dictionary of multiple key-value pairs to be appended. This fails silently since it's not matching the expected schema for policy entries.

Instead, write

import os
os.environ.update(
    {'GOOGLE_APPLICATION_CREDENTIALS': '<path-to-your-key-file>'}
)

import google.cloud.storage

storage_client = google.cloud.storage.Client()

bucket_name = '<your-bucket-name>'
bucket = storage_client.get_bucket(bucket_name)

policies = bucket.cors
policies.extend([
    {'origin': ['http://hello-world.example']},
    {'maxAgeSeconds': 3600}
])
bucket.cors = policies
bucket.update()
print(bucket.cors)

Note that the origin is a list of origins to receive CORS response headers as documented in the Storage JSON API web document. Other policies must be passed with the correct value type as well.

You can also choose to append each policy individually this way:

...
policies.append(
    {'origin': ['http://hello-world.example']},
)
policies.append(
    {'maxAgeSeconds': 3600}
)
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81