【问题标题】:Unable to use data from Google Cloud Storage in App Engine using Python 3无法使用 Python 3 在 App Engine 中使用来自 Google Cloud Storage 的数据
【发布时间】:2020-04-29 12:35:12
【问题描述】:

如何读取存储在项目的 Cloud Storage 存储桶中的数据并将其用于我在 App Engine 中编写的 Python 代码?

我尝试使用:

storage_client = storage.Client()

bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)

但我无法弄清楚如何从代码中提取实际数据以使其成为可用的形式。

任何帮助将不胜感激。

【问题讨论】:

  • 提取数据是什么意思?您实际上想要提取哪些数据?能举个例子吗?
  • 读取 blob(对象)。一种方法是将 blob 读入 Python 字符串:contents = blob.download_as_string()

标签: python-3.x google-app-engine google-cloud-platform google-cloud-storage google-app-engine-python


【解决方案1】:

从 Google Cloud Storage 存储桶获取文件意味着您只是获取了一个对象。这个概念从您的代码中抽象出文件本身。您需要将文件存储在本地以对其执行任何操作,或者根据文件的扩展名将该对象放入文件 readstreamer 或您需要读取文件的方法中。

您可以在此处查看如何从应用引擎读取文件的代码示例:

def read_file(self, filename):
  self.response.write('Reading the full file contents:\n')

  gcs_file = gcs.open(filename)
  contents = gcs_file.read()
  gcs_file.close()
  self.response.write(contents)

【讨论】:

    【解决方案2】:

    你有几个选择。

    1. content = blob.download_as_string() --> 将云存储对象的内容转换为字符串。
    2. blob.download_to_file(file_obj) --> 更新现有的 file_obj 以包含 Cloud Storage 对象内容。
    3. blob.download_to_filename(filename) --> 将对象保存在文件中。在 App Engine Standard 环境中,您可以将文件存储在 /tmp/ 目录中。

    更多信息请参考this link

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2014-11-22
      • 2014-03-22
      • 2015-05-14
      • 2016-09-12
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多