Skip to content

Instantly share code, notes, and snippets.

@tonghuikang
Created July 29, 2019 06:47
Show Gist options
  • Save tonghuikang/de49e5e3fb84cfaac545e44636c6f0f6 to your computer and use it in GitHub Desktop.
Save tonghuikang/de49e5e3fb84cfaac545e44636c6f0f6 to your computer and use it in GitHub Desktop.
Google Cloud Function to combine zip files
# source https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/functions/http/main.py
# [START functions_http_form_data]
from werkzeug.utils import secure_filename
import zipfile
import shutil
from flask import send_file
# [END functions_http_form_data]
# [START functions_http_form_data]
# Helper function that computes the filepath to save files to
def get_file_path(filename):
# Note: tempfile.gettempdir() points to an in-memory file system
# on GCF. Thus, any files in it must fit in the instance's memory.
file_name = secure_filename(filename)
return os.path.join(tempfile.gettempdir(), file_name)
def combine_zip_files(request):
""" Parses a 'multipart/form-data' upload request
This function show how you can
- receive zipfile from form-data
- unzip the zipfile into in-memory /tmp
- zip to make a zipfile in /tmp
- return the zipfile to the requestor
Args:
request (flask.Request): The request object.
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
"""
# This code will process each non-file field in the form
fields = {}
data = request.form.to_dict()
for field in data:
fields[field] = data[field]
print('Processed field: {} : {}'.format(field, data[field]))
# This code will process each file uploaded
files = request.files.to_dict()
for file_name, file in files.items():
file.save(get_file_path(file_name))
print('Processed file: %s' % file_name)
# Clear temporary directory
for file_name in files:
file_path = get_file_path(file_name)
file_path_zipfile = zipfile.ZipFile(file_path)
file_path_zipfile.extractall(path='/tmp')
os.remove(file_path)
files_list = os.listdir('/tmp')
for file_in_list in files_list:
print(file_in_list)
shutil.make_archive("/tmp/combined", 'zip', "/tmp/")
return send_file("/tmp/combined.zip", mimetype='application/zip')
# [END functions_http_form_data]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment