【问题标题】:How to read non-text file stored on Google Cloud Storage from Google Cloud Functions如何从 Google Cloud Functions 读取存储在 Google Cloud Storage 上的非文本文件
【发布时间】:2019-08-12 02:49:32
【问题描述】:

我需要从 Google Cloud Functions 读取文件。我要阅读的文件托管在 Google Cloud Storage 中。该文件不是阻止我使用 download_as_string 之类的文本文件。

到目前为止,我已经尝试以所有标准方式直接从对象中读取 gcs.open(file),但是没有定义 gcs(即使我确实在文件顶部将 cloudstorage 作为 gcs 导入)。

我能找到的最接近的东西是 how to read mp3 data from google cloud using python(我想读取 MP4 文件),但后来我尝试了,使用 blob_uri = gf.open(r'gs://' + bucket_name + '/' + file_name) 我总是收到以下错误 FileNotFoundError: [Errno 2] No such file or directory: gs://<yourbucket>/<filename>

我也试过bucket.get_blob(data['name'])bucket.get_blob(data)

因为是mp3文件,所以无法以字符串形式打开(如file = blobfile.download_as_string()

我还尝试使用请求尝试将文件转换为比特率,然后读取该数据,但是由于只读访问云功能需要创建一个新文件以打开现有文件,因此无法正常工作(我也尝试直接上传到云存储,但是因为 CS 返回一个博客,我无法写入文件)。

是否可以从 Google Cloud Functions 直接从托管在 Google Cloud Storage 上的(非文本)文件直接读取?如果是这样,我该怎么做?

【问题讨论】:

    标签: python google-cloud-firestore google-cloud-storage


    【解决方案1】:

    记住:blob 表示二进制大对象。因此是的,可以读取非字符串 blob!

    在 Python 中,您可以按照doc 中的说明进行download_to_filename

    【讨论】:

    • 因为这是在 Google Cloud Functions 中运行,而不是在 Google Cloud Storage 中运行,所以我不能 download_to_filename 这是我要解决的问题。
    • 为什么不能? blob 大小是否大于 1.5Gb?
    【解决方案2】:

    您可以读取驻留在谷歌云存储中的文件然后将它们用作文件系统的最佳方式,使用模块“gcsfs”。 在您的 requirements.txt 文件中包含 gcsfs。

    import gcsfs
    fs = gcsfs.GCSFileSystem(project=projectid)
    with fs.open(filename) as filename:
        file = filename.read()
    

    简单!

    【讨论】:

      【解决方案3】:

      我不确定您将什么导入为“gf”,但您遇到的错误可能是因为需要文件系统路径或字符串格式不正确。

      此外,您将无法将 blob 下载到文件系统,因为您无法使用 Cloud Functions 写入磁盘,但是您可以检索 blob 的二进制数据处理它并再次将其上传到存储桶。

      1.- 获取Blob:

      client = storage.Client()
      bucket = client.get_bucket("my-bucket")
      assert isinstance(bucket.get_blob("/path/to/blob.txt"), Blob)
      # <Blob: my-bucket, /path/to/blob.txt>
      assert not bucket.get_blob("/does-not-exist.txt")
      # None
      

      请注意,get_blob 函数需要存储桶内的相对路径。

      2.- 处理您的数据(记住这将是二进制数据)。

      3.- Upload 生成的 blob 到您的存储桶,您可以使用 upload_from_string 方法,因为文档声明它也接受二进制数据,但您必须将 content-type 指定为“application/octet-stream " 因为默认是“text/plain”,而您的二进制数据在技术上不是“mp3”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-07
        • 2021-04-18
        • 2018-07-22
        • 2019-11-17
        • 2018-04-22
        • 2013-01-26
        • 1970-01-01
        • 2019-07-11
        相关资源
        最近更新 更多