【问题标题】:How to check which path the file landed in Cloud Storage folders using Cloud Function如何使用 Cloud Function 检查文件落在 Cloud Storage 文件夹中的路径
【发布时间】:2020-01-13 01:40:11
【问题描述】:

我有一个 crontab 作业,它将新上传的文件获取到 FTP 并将它们存储在 Cloud Storage 存储桶中的不同文件夹中,如下所示: 如果文件是由 user1 发送的,则它位于 bucket/user1/file.csv 其他用户依此类推。

下一步是我想处理 Cloud Function 附带的每个文件,根据新文件所在的路径对新文件应用更改并将其保存在另一个存储桶中。 知道 Cloud Function 只能通过存储桶触发,我想包含一个 IF 语句,检查新文件是否位于 user1 文件夹中,然后执行 function1 elseif user2 然后 function2 等等。

但是,直到现在我才能够通过代码来解决它。

【问题讨论】:

    标签: python-3.x triggers google-cloud-functions google-cloud-storage


    【解决方案1】:

    在 Cloud Function 中,您拥有 "event" 对象的范围,该对象具有 "id" 属性。

    此 id 符合:

    'bucket_name/folder_or_subfolder_name/newly_created_or_updated_object_name/object_generated_id'
    

    因此,如果您只剪切最后两个部分,您将获得对象所在的路径,您还可以隔离对象正上方的文件夹。

    您还可以根据条件声明其他函数并相应地引用 then,只需确保在创建云函数时“要执行的函数”字段中包含“主”函数(在这种情况下为“你好_gcs”。

    以下是 Python3 中的示例:

    def hello_gcs(event, context):
        """Triggered by a change to a Cloud Storage bucket.
        Args:
             event (dict): Event payload.
             context (google.cloud.functions.Context): Metadata for the event.
        """
        word = "dir-name"
    
        path = event["id"].rsplit("/",2) 
        parent_folder = event["id"].rsplit("/",3) 
    
        path = path[0]
        parent_folder = parent_folder[1]
    
        if parent_folder == word:
            one()
        else:
            two()
    
    
    def one():
        print(f"You have entered function one")
    
    
    def two():
        print(f"You have entered function two")
    

    您可以进行更多操作以适应您的用例。

    【讨论】:

    • 看它的绝妙方式非常感谢@Mayeru
    • 很高兴知道这很有帮助,我编辑了我的答案,添加了一个如何执行条件的示例,但是这是一般示例,因为我不确定您使用哪个标准来选择要做什么一个用户到另一个用户。
    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2021-06-16
    相关资源
    最近更新 更多