python - 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
解决方案
您从 Google Storage 读取的字符串是多部分形式的字符串表示形式。它不仅包含上传的文件内容,还包含一些元数据。同一种请求可用于表示多个文件和/或表单字段以及一个文件。
要访问您想要的文件内容,您可以使用支持该内容的库,例如requests-toolbelt
. 查看此 SO 答案以获取示例。如果绝对必须,您将需要包含边界的 Content-Type 标头,或者仅从内容中手动解析边界。
编辑:根据您的回答,似乎 Content-Type 标头在 Google Storage 的存储元数据中可用,这是一种常见情况。对于此答案的未来读者,从何处读取此标题的具体细节将取决于您的具体情况。
由于此库存在于PyPI(Python 包索引)中,因此您甚至可以通过在文件中将其指定为依赖requirements.txt
项来在 Cloud Functions 中使用它。
推荐阅读
- angular - ngx-card - 角度通用构建中的卡指令失败
- javascript - Draw.io 嵌入模式 - 自定义编辑链接表单
- string - 不能在字符串映射中使用基础类型的字符串:“不能使用
(类型 ) 作为地图索引中的类型字符串" - sql-server-2016 - 在 mssql 中获取当前月份的第一、第二、第三周日期,下个月是什么日期
- spartacus-storefront - 将加载新数据添加到 Store 的最佳位置是什么?ngrx/商店
- angular7 - 更新后未刷新垫表
- ios - 如何找出对象的方法何时被调用?
- sql - SQL 按聚合 varchar 列分组
- c - 从 C 中的函数返回二维数组
- elasticsearch - 如何在elasticsearch中按结果聚合分组