Team Ai
Apppublic

Underground-Digital/Workflow-Engine

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
google_cloud_storage.py61 linesDownload Raw Back to storage
1import base642import io3import json4from collections.abc import Generator5 6from google.cloud import storage as google_cloud_storage7 8from configs import dify_config9from extensions.storage.base_storage import BaseStorage10 11 12class GoogleCloudStorage(BaseStorage):13    """Implementation for Google Cloud storage."""14 15    def __init__(self):16        super().__init__()17 18        self.bucket_name = dify_config.GOOGLE_STORAGE_BUCKET_NAME19        service_account_json_str = dify_config.GOOGLE_STORAGE_SERVICE_ACCOUNT_JSON_BASE6420        # if service_account_json_str is empty, use Application Default Credentials21        if service_account_json_str:22            service_account_json = base64.b64decode(service_account_json_str).decode("utf-8")23            # convert str to object24            service_account_obj = json.loads(service_account_json)25            self.client = google_cloud_storage.Client.from_service_account_info(service_account_obj)26        else:27            self.client = google_cloud_storage.Client()28 29    def save(self, filename, data):30        bucket = self.client.get_bucket(self.bucket_name)31        blob = bucket.blob(filename)32        with io.BytesIO(data) as stream:33            blob.upload_from_file(stream)34 35    def load_once(self, filename: str) -> bytes:36        bucket = self.client.get_bucket(self.bucket_name)37        blob = bucket.get_blob(filename)38        data = blob.download_as_bytes()39        return data40 41    def load_stream(self, filename: str) -> Generator:42        bucket = self.client.get_bucket(self.bucket_name)43        blob = bucket.get_blob(filename)44        with blob.open(mode="rb") as blob_stream:45            while chunk := blob_stream.read(4096):46                yield chunk47 48    def download(self, filename, target_filepath):49        bucket = self.client.get_bucket(self.bucket_name)50        blob = bucket.get_blob(filename)51        blob.download_to_filename(target_filepath)52 53    def exists(self, filename):54        bucket = self.client.get_bucket(self.bucket_name)55        blob = bucket.blob(filename)56        return blob.exists()57 58    def delete(self, filename):59        bucket = self.client.get_bucket(self.bucket_name)60        bucket.delete_blob(filename)61