python 谷歌云函数解压文件

Rak*_*007 3 python google-cloud-storage google-cloud-platform google-cloud-functions

我是 GCP 的新手,有 Python 经验。我试图为一个场景编写一个云函数来解压 GCS 中的文件并将它们复制到另一个存储桶。

from google.cloud import storage
import tarfile

client = storage.Client()

def untar_lookupfiles(data, context):
    # Get the file that has been uploaded to GCS
    bucket = client.get_bucket(data['Source_bucketName'])

    #copy the tarfiles to another bucket
    bucket = client.get_bucket('Target_bucketName')
    blob = bucket.blob('gs://path/to/file.name')
    blob.upload_from_filename('/path/to/source.file')

    # Untar the files
    print('Untaring Files: {}'.format(data['name']))
    untar = tarfile.open("marfiles.tar.gz", "r:gz") # filename is hard coded should be replaced with data['name']
    untar.extractall(path=dir)
Run Code Online (Sandbox Code Playgroud)

但是这段代码中似乎缺少某些东西,有人可以帮我编写代码吗?我没有使用 nodejs 编写代码的经验。感谢你的帮助。

Dus*_*ram 6

这是一个函数,它将解压缩放在一个存储桶中的文件并将内容放入另一个存储桶:

requirements.txt

google-cloud-storage
Run Code Online (Sandbox Code Playgroud)

main.py

import io
import os
import tarfile

from google.cloud import storage

client = storage.Client()
input_bucket = client.get_bucket('INPUT-BUCKET-NAME')
output_bucket = client.get_bucket('OUTPUT-BUCKET-NAME')


def untar(data, context):
    # Get the contents of the uploaded file
    input_blob = input_bucket.get_blob(data['name']).download_as_string()

    # Turn the upload file into a tar file
    tar = tarfile.open(fileobj=io.BytesIO(input_blob))

    # Iterate over all files in the tar file
    for member in tar.getnames():

        # Extract the individual file
        file_object = tar.extractfile(member)

        # Check if it's a file or directory (which should be skipped)
        if file_object:

            # Create a new blob instance in the output bucket
            output_blob = output_bucket.blob(os.path.join(data['name'], member))

            # Write the contents of the file to the output blob
            output_blob.upload_from_string(file_object.read())
Run Code Online (Sandbox Code Playgroud)

部署:

$ gcloud beta functions deploy test \
    --runtime python37 \
    --project PROJECT_NAME \
    --trigger-resource INPUT_BUCKET_NAME \
    --trigger-event google.storage.object.finalize
Run Code Online (Sandbox Code Playgroud)