google_cloud_storage.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import base64
  2. import io
  3. import json
  4. from collections.abc import Generator
  5. from flask import Flask
  6. from google.cloud import storage as google_cloud_storage
  7. from extensions.storage.base_storage import BaseStorage
  8. class GoogleCloudStorage(BaseStorage):
  9. """Implementation for Google Cloud storage."""
  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_str = app_config.get("GOOGLE_STORAGE_SERVICE_ACCOUNT_JSON_BASE64")
  15. # if service_account_json_str is empty, use Application Default Credentials
  16. if service_account_json_str:
  17. service_account_json = base64.b64decode(service_account_json_str).decode("utf-8")
  18. # convert str to object
  19. service_account_obj = json.loads(service_account_json)
  20. self.client = google_cloud_storage.Client.from_service_account_info(service_account_obj)
  21. else:
  22. self.client = google_cloud_storage.Client()
  23. def save(self, filename, data):
  24. bucket = self.client.get_bucket(self.bucket_name)
  25. blob = bucket.blob(filename)
  26. with io.BytesIO(data) as stream:
  27. blob.upload_from_file(stream)
  28. def load_once(self, filename: str) -> bytes:
  29. bucket = self.client.get_bucket(self.bucket_name)
  30. blob = bucket.get_blob(filename)
  31. data = blob.download_as_bytes()
  32. return data
  33. def load_stream(self, filename: str) -> Generator:
  34. def generate(filename: str = filename) -> Generator:
  35. bucket = self.client.get_bucket(self.bucket_name)
  36. blob = bucket.get_blob(filename)
  37. with blob.open(mode="rb") as blob_stream:
  38. while chunk := blob_stream.read(4096):
  39. yield chunk
  40. return generate()
  41. def download(self, filename, target_filepath):
  42. bucket = self.client.get_bucket(self.bucket_name)
  43. blob = bucket.get_blob(filename)
  44. blob.download_to_filename(target_filepath)
  45. def exists(self, filename):
  46. bucket = self.client.get_bucket(self.bucket_name)
  47. blob = bucket.blob(filename)
  48. return blob.exists()
  49. def delete(self, filename):
  50. bucket = self.client.get_bucket(self.bucket_name)
  51. bucket.delete_blob(filename)