检查 blob 是否存在

Check if blob exists

我正在尝试构建一个 DAG,它首先检查 Google 云存储中的给定 path/blob 是否存在。 blob 是包含一些 RAW 数据的,而不是安装在 Composer worker 上的。

或者,一次性查看它是否存在并包含文件 (list > 1) 会很方便,但返回存在已经是一件好事。

到目前为止,我尝试通过 bash 命令、google.cloud.storage 库和 gcs_hook 使用 gsutil stats,但均无济于事。所有这些 return 对于我非常确定存在的文件夹都是错误的

def check_folder(templates_dict,**kwargs):
    bucket = 'bucketname'
    blob_name = templates_dict['blob_name']
    # Blob name is something along the lines of '2019-04-10/11/' 
    gcs = GoogleCloudStorageHook()
    flag = gcs.exists(bucket,blob_name)
    if flag:
        print(flag)
        return('this_is_true')
    else:
        print(flag)
        return('this_is_not_true')

对于给定的 blob_name,我很确定它存在,我期待一个 true,但它总是 returns False。知道发生了什么事吗?谢谢!

GoogleCloudStorageHook 中的 exists 函数检查对象,不支持使用前缀。如果您想检查给定前缀中是否有任何数据,您需要使用 list 函数。

示例:

if bool(hook.list(bucket, prefix=prefix)):
    print('some data is in my folder!')

您可能还想查看传感器的实现 GoogleCloudStoragePrefixSensor,因为它与您正在做的非常相似。