如何通过google-cloud-storage Python库修改GCS文件主元数据字段?
解决GCS主元数据修改无效的问题
问题原因
你当前的代码将cache-control、content-disposition这类主元数据字段放到了gcs_blob.metadata中,但metadata属性仅用于自定义元数据(带x-goog-meta-前缀的字段)。主元数据需要直接设置Blob对象对应的专属属性,不能通过metadata赋值。
正确实现代码
针对你使用的google-cloud-storage 2.3.0版本,修正后的代码如下:
def _open_gcs_file_for_write(gcs_blob, mode='w', options=None, content_type=None): """ Helper function to open a GCS file for writing. """ if options or content_type: # 逐个处理主元数据字段 if options: if 'cache-control' in options: gcs_blob.cache_control = options['cache-control'] if 'content-disposition' in options: gcs_blob.content_disposition = options['content-disposition'] if 'content-encoding' in options: gcs_blob.content_encoding = options['content-encoding'] # 如需添加其他主元数据,按此格式扩展即可,比如content-language等 # 处理content_type字段 if content_type: gcs_blob.content_type = content_type # 提交元数据更新 gcs_blob.patch() options = { 'cache-control': 'max-age=3600', 'content-disposition': 'inline; filename="example.txt"', 'content-encoding': 'gzip' }
关键说明
- 主元数据字段对应Blob对象的驼峰命名属性:
cache-control→cache_controlcontent-disposition→content_dispositioncontent-encoding→content_encoding
metadata属性仅用于自定义元数据,比如你自己定义的x-goog-meta-custom-key,需以{'custom-key': 'value'}的字典形式传入patch()方法只会更新已修改的属性,不会覆盖未改动的元数据
内容的提问来源于stack exchange,提问作者Alex_the_Shadowalker
相关产品推荐
相关产品推荐

