通过 Python(云功能)从 Google 云存储中解压缩并读取 .gz 文件

Unzip and read a .gz file from Google Cloud storage via Python (Cloud Function)

我必须从 python 中的 google 云存储中读取一个解压缩文件(云函数)。 我尝试了以下方法,但 CF 每次都会崩溃。 GCS 中的文件:ABC.gz

import gzip  

def process(data, context):  
    filename = data['name']  
    with gzip.open("'"+filename+"'", 'rb') as f:  
        file_content = f.read()

求推荐。

这是预期的行为。当您的函数由 Cloud Storage 事件触发时,您只会获得包含事件 data 的字典,而不是对象本身。

您应该使用 data 字典中的 namebucket 从云存储中获取对象。这是一个代码,可以指导您获取从 here:

中获取的文件
import gzip
from google.cloud import storage

def process(data, context):
    storage_client = storage.Client()

    bucket = storage_client.bucket(data['bucket'])
    blob = bucket.blob(data['name'])
    blob.download_to_filename("/tmp/" + data['name'])

    #Here goes your code to unzip the file

考虑到您可能需要将所需的库添加到 requirements.txt 文件,并向函数的 Runtime Service Account 授予访问云存储所需的权限。