如何从python google cloud函数访问google cloud存储中文件的文件元数据 [英] How to access file metadata, for files in google cloud storage, from a python google cloud function

查看:406
本文介绍了如何从python google cloud函数访问google cloud存储中文件的文件元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Cloud Function中访问Google云存储中文件上的自定义元数据,但它始终返回"None".

I'm trying to access the custom metadata on a file in Google cloud storage from within a Cloud Function, but it always returns "None".

  • 该文件上肯定有自定义元数据-可以从GCS浏览器中看到自定义元数据.

  • The file definitely has custom metadata on it - the custom metadata can be seen from the GCS browser.

如果我在云外壳环境中运行代码,则可以成功访问自定义元数据.

I can access the custom metadata successfully if I run my code in a cloud shell environment.

但是,如果我在云函数中运行相同的代码,则返回的blob.metadata始终为"None".

But if I run the same code in a cloud function, then the returned blob.metadata is always "None".

我做错了什么?与Cloud Shell相比,我在Cloud Function中必须做些什么.

What am I doing wrong? What do I have to do differently in a Cloud Function compared to a Cloud Shell.

from google.cloud import storage
client = storage.Client()
bucket = client.bucket(<my bucket name>)
blob = bucket.get_blob(<my filename>)
metadata = blob.metadata

还请注意,blob.download_as_string()可以正确获取文件内容-这只是我无法获取的自定义元数据.

Note also that blob.download_as_string() gets me the file contents correctly - it's just the custom metadata I can't get.

推荐答案

blob.metadata仅返回存储对象的 自定义元数据 (字典). None表示没有自定义元数据.请参见 metadata 的文档:

blob.metadata only returns Storage object's custom metadata (a dict). None means that there is no custom metadata. See the docs of metadata :

检索对象的任意/特定于应用程序的元数据.

Retrieve arbitrary/application specific metadata for the object.

Object资源(API)的文档指定metadata为:

The documentation of Object resource (API) specify that metadata is :

用户提供的元数据,以键/值对的形式出现.

User-provided metadata, in key/value pairs.

请注意,自定义元数据与固定键元数据不同,您还可以使用Google Cloud Console中的编辑元数据按钮进行编辑.固定键元数据包含:

Note that custom metadata is different from fixed-key metadata, that you can also edit with Edit metadata button in Google Cloud Console. Fixed-key metadata contains :

  • 内容类型
  • 内容编码
  • 内容处置
  • 内容语言
  • 缓存控制

可以通过blob.content_typeblob.content_encoding,...访问这种特殊类型的元数据(请检查完整示例).

This particular kind of metadata can be accessed via blob.content_type, blob.content_encoding, ... (check a complete example).

要添加自定义元数据,只需在同一窗口中单击添加项目按钮(编辑元数据)或使用gsutil(请参阅

To add custom metadata, just click Add item button on the same window (Edit metadata) or use gsutil (see Editing object metadata docs) :

gsutil setmeta -h "x-goog-meta-examplekey:examplevalue" gs://<your-bucket>

这篇关于如何从python google cloud函数访问google cloud存储中文件的文件元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆