Google 未使用 python 客户端设置云存储桶 CORS 配置

Google Cloud storage bucket CORS configuration not getting set using python client

未使用 python 设置云存储桶的 CORS 配置。

我正在执行以下步骤:http://google-cloud-python.readthedocs.io/en/latest/storage/buckets.html#google.cloud.storage.bucket.Bucket.cors

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

如果我按照上述步骤获得存储桶的 CORS 配置,它会给出一个空列表。

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

由于您没有确切地分享您更新 CORS 条目的方式,我假设您传递的是要附加的多个 key-value 对的字典。这会无提示地失败,因为它与策略条目的预期架构不匹配。

改为写

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)

请注意,源是接收 CORS 响应 headers 的源列表,如 Storage JSON API web document 中所述。其他策略也必须使用正确的值类型传递。

您也可以选择以这种方式单独附加每项政策:

...
policies.append(
    {'origin': ['http://hello-world.example']},
)
policies.append(
    {'maxAgeSeconds': 3600}
)