如何在Ruby中通过Google Cloud Function读取Google Cloud Storage文件内容?
Google Cloud Function读取GCS文件实现方案及乱码问题修复
可行性说明
完全支持通过Google Cloud Function读取GCS存储的文件内容,只需为Cloud Function运行服务账号配置GCS文件的读取权限即可。
前置配置
- 给Cloud Function关联的服务账号授予目标Bucket的
storage.objects.get权限 - 在函数的
requirements.txt中添加依赖:google-cloud-storage>=2.10.0
标准实现代码
文本类文件(txt/json/csv等)读取
from google.cloud import storage # 初始化GCS客户端 storage_client = storage.Client() # 指定目标Bucket bucket = storage_client.get_bucket("替换为你的Bucket名称") # 指定目标文件路径 blob = bucket.blob("替换为文件在Bucket内的完整路径,例如data/test.txt") # 方法1:直接读取为文本,自动处理字节解码 content = blob.download_as_text(encoding="utf-8") # 方法2:先读字节再手动解码,适合需要自定义处理的场景 # raw_bytes = blob.download_as_bytes() # content = raw_bytes.decode("utf-8")
大文件流式读取
避免大文件全量加载占满内存,可使用流式读取:
with blob.open("r", encoding="utf-8") as f: for line in f: # 逐行处理内容 print(line.strip())
二进制文件(图片/压缩包等)读取
不需要解码,直接获取字节流处理即可:
raw_bytes = blob.download_as_bytes()
乱码问题修复
你遇到的\xA3\xB4\x97类输出不是异常,是未解码的原始字节流,问题来源两个:
- 代码写法错误:
file.download.read是无效写法,GCS SDK没有该属性,需使用上述标准的download_as_text/download_as_bytes方法 - 未指定正确编码:如果文件编码不是默认utf-8,可手动指定对应编码,比如
encoding="gbk";如果不确定文件编码,可使用chardet库自动检测:
import chardet raw_bytes = blob.download_as_bytes() detect_result = chardet.detect(raw_bytes) content = raw_bytes.decode(detect_result["encoding"])
使用chardet需要在requirements.txt添加依赖:chardet>=5.2.0
内容的提问来源于stack exchange,提问作者kokeshi
相关产品推荐
相关产品推荐

