【问题标题】:Accessing and using csv file from Cloud Storage in Cloud Run instance在 Cloud Run 实例中访问和使用 Cloud Storage 中的 csv 文件
【发布时间】:2022-01-04 05:39:31
【问题描述】:

我知道如何从云运行实例中的云存储下载文件。但是,我找不到在 python 中读取文件的语法。我希望通过使用pd.read_csv('testing.csv') 立即将 csv 文件转换为 pandas 数据帧。所以我的个人代码看起来像, download_blob(bucket_name, source_blob_name, 'testing.csv')。那么我不应该能够在云运行实例中执行pd.read_csv('testing.csv') 吗?这样做时,我在加载页面时不断获得内部服务器。这似乎是一个简单的问题,但我无法在任何地方找到它的示例。一切都只是下载文件,我从来没有看到它被使用过。



def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object
    # source_blob_name = "storage-object-name"

    # The path to which the file should be downloaded
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Downloaded storage object {} from bucket {} to local file {}.".format(
            source_blob_name, bucket_name, destination_file_name
        )
    )

【问题讨论】:

    标签: python csv google-cloud-platform google-cloud-storage google-cloud-run


    【解决方案1】:

    使用 'testing.csv' 等文件名表示将文件写入当前目录。当前目录是什么?而是指定一个已知目录位置的绝对路径。

    下载到/tmp/目录,例如'/tmp/testing.csv'。使用文件系统空间会消耗内存,因为文件系统是基于 RAM 的。确保 Cloud Run 实例有足够的内存。

    Excerpt from Cloud Run Container Runtime Contact:

    你的容器的文件系统是可写的,并且受制于以下行为:

    • 这是一个内存文件系统,因此写入它会使用容器实例的内存。
    • 当容器实例停止时,写入文件系统的数据不会保留。

    Reference: Filesystem access

    【讨论】:

      【解决方案2】:

      download_as_bytes 是您要查找的函数,如果您想将其直接加载到内存中。

      storage_client = storage.Client()
      bucket = storage_client.bucket(bucket_name)
      blob = bucket.blob(source_blob_name)
      data = blob.download_as_bytes()
      pd.read_csv(StringIO(data))
      

      https://googleapis.dev/python/storage/latest/blobs.html#google.cloud.storage.blob.Blob.download_as_bytes

      Pandas 还支持直接从 Google Cloud Storage 读取。 https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html

      任何有效的字符串路径都是可接受的。该字符串可以是一个 URL。有效的 URL 方案包括 http、ftp、s3、gs 和文件。

      类似“gs://bucket/file”

      【讨论】:

      • 想给你一个赞成票,因为我最终确实使用了@John_Hanley 对另一个文件的回答,在这种情况下,它直接回答了我的问题。但是,我也使用 pandas 直接从 GCS 读取数据。感谢您的帮助!
      猜你喜欢
      • 2022-08-18
      • 2019-09-27
      • 2021-06-16
      • 2021-01-21
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2020-11-05
      • 2019-10-28
      相关资源
      最近更新 更多