首页 > 解决方案 > GCP Python 云函数:从云存储中读取纯文本文件

问题描述

一旦文件上传到存储中,就会触发云功能,我的文件名:PubSubMessage。内文:嗨,这是第一条消息

from google.cloud import storage
storage_client = storage.Client()

def hello_gcs(event, context):
file = event

bucket = storage_client.get_bucket(file['bucket'])

blob = bucket.blob(file['name'])

contents = blob.download_as_string()
print('contents: {}'.format(contents))

decodedstring = contents.decode(encoding="utf-8", errors="ignore")
print('decodedstring: \n{}'.format(decodedstring))

print('decodedstring: \n{}'.format(decodedstring))

------WebKitFormBoundaryAWAKqDaYZB3fJBhx
Content-Disposition: form-data; name="file"; filename="PubSubMessage.txt"
Content-Type: text/plain

Hi, this this the first line.
Hi ,this is the second line. 

hi this is the space after.
------WebKitFormBoundaryAWAKqDaYZB3fJBhx--

我的Requirements.txt 文件

google-cloud-storage
requests==2.20.0
requests-toolbelt==0.9.1

我如何获得文件“嗨,我是第一条消息.....”中的实际字符串?

从文件中获取文本的最佳方法是什么?TIA

标签: pythongoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storage

解决方案


您从 Google Storage 读取的字符串是多部分形式的字符串表示形式。它不仅包含上传的文件内容,还包含一些元数据。同一种请求可用于表示多个文件和/或表单字段以及一个文件。

要访问您想要的文件内容,您可以使用支持该内容的库,例如requests-toolbelt. 查看此 SO 答案以获取示例。如果绝对必须,您将需要包含边界的 Content-Type 标头,或者仅从内容中手动解析边界。

编辑:根据您的回答,似乎 Content-Type 标头在 Google Storage 的存储元数据中可用,这是一种常见情况。对于此答案的未来读者,从何处读取此标题的具体细节将取决于您的具体情况。

由于此库存在于PyPI(Python 包索引)中,因此您甚至可以通过在文件中将其指定为依赖requirements.txt项来在 Cloud Functions 中使用它。


推荐阅读