google_storage.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import base64
  2. from collections.abc import Generator
  3. from contextlib import closing
  4. from flask import Flask
  5. from google.cloud import storage as GoogleCloudStorage
  6. from extensions.storage.base_storage import BaseStorage
  7. class GoogleStorage(BaseStorage):
  8. """Implementation for google storage.
  9. """
  10. def __init__(self, app: Flask):
  11. super().__init__(app)
  12. app_config = self.app.config
  13. self.bucket_name = app_config.get('GOOGLE_STORAGE_BUCKET_NAME')
  14. service_account_json = base64.b64decode(app_config.get('GOOGLE_STORAGE_SERVICE_ACCOUNT_JSON_BASE64')).decode(
  15. 'utf-8')
  16. self.client = GoogleCloudStorage.Client().from_service_account_json(service_account_json)
  17. def save(self, filename, data):
  18. bucket = self.client.get_bucket(self.bucket_name)
  19. blob = bucket.blob(filename)
  20. blob.upload_from_file(data)
  21. def load_once(self, filename: str) -> bytes:
  22. bucket = self.client.get_bucket(self.bucket_name)
  23. blob = bucket.get_blob(filename)
  24. data = blob.download_as_bytes()
  25. return data
  26. def load_stream(self, filename: str) -> Generator:
  27. def generate(filename: str = filename) -> Generator:
  28. bucket = self.client.get_bucket(self.bucket_name)
  29. blob = bucket.get_blob(filename)
  30. with closing(blob.open(mode='rb')) as blob_stream:
  31. while chunk := blob_stream.read(4096):
  32. yield chunk
  33. return generate()
  34. def download(self, filename, target_filepath):
  35. bucket = self.client.get_bucket(self.bucket_name)
  36. blob = bucket.get_blob(filename)
  37. with open(target_filepath, "wb") as my_blob:
  38. blob_data = blob.download_blob()
  39. blob_data.readinto(my_blob)
  40. def exists(self, filename):
  41. bucket = self.client.get_bucket(self.bucket_name)
  42. blob = bucket.blob(filename)
  43. return blob.exists()
  44. def delete(self, filename):
  45. bucket = self.client.get_bucket(self.bucket_name)
  46. bucket.delete_blob(filename)