How to access file metadata, for files in google cloud storage, from a python google cloud function(如何从 python 谷歌云函数访问文件元数据,用于谷歌云存储中的文件)
问题描述
我正在尝试从 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.
如果我在云 shell 环境中运行我的代码,我可以成功访问自定义元数据.
I can access the custom metadata successfully if I run my code in a cloud shell environment.
但如果我在云函数中运行相同的代码,则返回的 blob.metadata 始终为无".
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
只返回 Storage 对象的 自定义元数据(字典).None
表示没有自定义元数据.请参阅 元数据
的文档:
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 中的 Edit metadata 按钮进行编辑.固定键元数据包含:
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_type
、blob.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 谷歌云函数访问文件元数据,用于谷歌云存储中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!