Skip to content

Instantly share code, notes, and snippets.

@pior
Created October 10, 2017 21:19
Show Gist options
  • Save pior/955a9b4013701a8332c791947349b925 to your computer and use it in GitHub Desktop.
Save pior/955a9b4013701a8332c791947349b925 to your computer and use it in GitHub Desktop.
import google.cloud.exceptions
import google.cloud.storage
class GCSFileStore:
def __init__(self, credentials_path, bucket_name):
Client = google.cloud.storage.Client
client = Client.from_service_account_json(credentials_path)
self._bucket = client.bucket(bucket_name)
def write_file(self, project_id, version_id, filepath, fp):
blob = self._get_blob(project_id, version_id, filepath)
blob.upload_from_file(file_obj=fp)
def read_file(self, project_id, version_id, filepath) -> bytes:
blob = self._get_blob(project_id, version_id, filepath)
try:
return blob.download_as_string()
except google.cloud.exceptions.NotFound:
return None
def _get_blob(self, project_id, version_id, filepath):
filepath = filepath.lstrip('/')
path = f'{project_id}/{version_id}/{filepath}'
return self._bucket.blob(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment