Облачная функция Google Python для распаковки файлов

1

Я новичок в GCP, имею опыт работы с Python. Я попытался написать Cloud Function для сценария для распаковки файлов в 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)

Но похоже, что в этом коде что-то отсутствует, может кто-то помочь мне с кодом. У меня нет опыта работы с nodejs для написания кода. Ценю твою помощь.

  • 2
    Какую ошибку вы получаете?
  • 0
    Я не вижу, где бы вы ни использовали переменную tarfiles после того, как вы заполнили ее данными. Вы tarfile виду tarfile ?
Показать ещё 3 комментария
Теги:
google-cloud-platform
google-cloud-storage
google-cloud-functions

1 ответ

1
Лучший ответ

Здесь функция, которая разобьет файл, помещенный в одно ведро, и поместит содержимое в другое ведро:

В requirements.txt:

google-cloud-storage

В 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 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())

Развернуть:

$ gcloud beta functions deploy test \
    --runtime python37 \
    --project PROJECT_NAME \
    --trigger-resource INPUT_BUCKET_NAME \
    --trigger-event google.storage.object.finalize
  • 0
    Большое спасибо, Дастин, код работал как charm, я пытаюсь проверить, заканчивается ли файл на tar.gz, так как несколько файлов попадают одновременно в область ввода. позвольте мне самому разобраться, еще раз спасибо
  • 0
    Я попытался повторно использовать ваш код и написал ниже код, чтобы распаковать файл и скопировать в другое ведро. Вы можете исправить меня, если я ошибаюсь def untar(data, context): # Get the contents of the uploaded file input_blob = input_bucket.get_blob(data['name']).download_as_string() # check filename endswith "csv.gz" if data['name'].endswith('csv.gz'): gz = gzip.open(fileobj=io.BytesIO(input_blob)) output_blob = output_bucket.blob(os.path.join(data['name'], gz)) output_blob.upload_from_string(file_object.read())
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню