【发布时间】:2021-05-31 17:25:13
【问题描述】:
当文件成功上传到给定的 Google Cloud Storage 存储桶(“Object Finalize”)时,我想设置一个触发器,让该文件名可以在正在运行的 VM 中访问。
有一个标准的云函数在文件上传时监听,触发google.storage.object.finalize:
def hello_gcs(event, context):
"""Background Cloud Function to be triggered by Cloud Storage.
This generic function logs relevant data when a file is changed.
Args:
event (dict): The dictionary with data specific to this type of event.
The `data` field contains a description of the event in
the Cloud Storage `object` format described here:
https://cloud.google.com/storage/docs/json_api/v1/objects#resource
context (google.cloud.functions.Context): Metadata of triggering event.
Returns:
None; the output is written to Stackdriver Logging
"""
print('Event ID: {}'.format(context.event_id))
print('Event type: {}'.format(context.event_type))
print('Bucket: {}'.format(event['bucket']))
print('File: {}'.format(event['name']))
print('Metageneration: {}'.format(event['metageneration']))
print('Created: {}'.format(event['timeCreated']))
print('Updated: {}'.format(event['updated']))
https://cloud.google.com/functions/docs/calling/storage#functions-calling-storage-python
(我正在使用 Python,但我很乐意使用提供的任何其他语言)
假设我有一个名为“my-instance”的 VM:有没有办法将文件名从 event['name'] 传递给 VM,以便 VM 中的代码可以访问它?
还有其他 SO 问题讨论如何直接从 Cloud Storage 读取文件,例如Read csv from Google Cloud storage to pandas dataframe
import pandas as pd
import gcsfs
fs = gcsfs.GCSFileSystem(project='my-project')
with fs.open('bucket/path.csv') as f:
df = pd.read_csv(f)
但是如何将文件名从 google.storage.object.finalize 传递到 VM 以运行此代码?
【问题讨论】:
-
您能澄清一下“将文件名从事件['name'] 传递到 VM”下的确切含义吗?您是否认为这种“通过”很大程度上取决于您在该 VM 中运行的“代码”?你的“代码”应该如何知道这些信息?你也要修改那个“代码”吗?
-
嗨@al-dann,感谢您的帮助。通过“通过”,我指的是放置在存储桶中的文件的触发器。一旦发生该事件,VM 如何访问该确切文件?在带有
path.csv的python pandas 示例中,一旦path.csv被上传到bucket,pandas 代码如何访问它?关于 VM 中的代码,是的,我很乐意对其进行编辑。这有意义吗? -
我还是不明白你的“代码”如何接受外部事件。例如,假设您的代码可以每分钟扫描 VM 中的某个目录。如果那里出现一个新文件,您的代码可以做一些有用的事情。或者假设您的“代码”可以收听 PubSub 订阅,因此,当那里出现一条消息时 - 可以调用您的“代码”中的某些功能。你在虚拟机中的“代码”可以做这样的事情吗?
-
接下来的问题——你真的需要一个虚拟机来运行你的“代码”——它可以是一个云函数吗?云跑?数据流?应用引擎? - 而不是虚拟机?
-
让我们使用
python script.py path.csv的示例,其中script.py解析参数。这有意义吗?对于另一个问题,我需要满足一些内存要求。
标签: python google-cloud-platform google-cloud-functions google-cloud-storage