Skip to content

Instantly share code, notes, and snippets.

@tomestephens
Last active November 12, 2018 22:01
Show Gist options
  • Save tomestephens/4cac63776b8e6e8f80bbd9a0ba5fd9b1 to your computer and use it in GitHub Desktop.
Save tomestephens/4cac63776b8e6e8f80bbd9a0ba5fd9b1 to your computer and use it in GitHub Desktop.
Simple Python class for working with GCP Buckets
import os
import tempfile
from google.cloud import storage
from google.cloud.storage import Blob
class BucketManager(object):
def __init__(self, bucket_name):
self._storage_client = storage.Client()
self._bucket = self._storage_client.get_bucket(bucket_name)
def download(self, blob_name):
# from blob name get the file name
file_name = blob_name.split('/')[-1]
# create a temporary directory
tmp = os.path.join(tempfile.gettempdir(), file_name)
blob = self._bucket.blob(blob_name)
blob.download_to_filename(tmp)
return tmp
def upload(self, blob_path, file_path):
blob = self._bucket.blob('{}/{}'.format(blob_path, os.path.basename(file_path)))
blob.upload_from_filename(file_path)
def delete(self, blob_name):
blob = self._bucket.blob(blob_name)
blob.delete()
def delete_dir(self, path):
for blob in self._bucket.list_blobs():
if path in blob.path:
blob.delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment