Skip to content

Instantly share code, notes, and snippets.

@djaquels
Created March 12, 2022 17:45
Show Gist options
  • Save djaquels/f009f6916fac45c5f46560be29628c89 to your computer and use it in GitHub Desktop.
Save djaquels/f009f6916fac45c5f46560be29628c89 to your computer and use it in GitHub Desktop.
Cloud Function to Compress Cloud Storage Folders
from google.cloud import storage
from zipfile import ZipFile
import os
def compress(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP 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>`.
"""
request_json = request.get_json()
print(request_json)
client = storage.Client()
bucket_name = request_json["bucket_name"]
bucket = client.get_bucket(bucket_name)
folder = request_json["folder"]
#compressing files
zipObj = ZipFile('/tmp/folder.zip', 'w')
for blob in client.list_blobs(bucket_name, prefix=folder):
#blob = bucket.get_blob(filename)
if blob.name == folder:
continue
print(blob.name)
zipObj.writestr(str(blob.name), blob.download_as_bytes())
zipObj.close()
new_blob = bucket.blob('{}/{}.zip'.format(folder,folder))
new_blob.upload_from_filename(filename='/tmp/folder.zip')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment