supabase_storage.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import io
  2. from collections.abc import Generator
  3. from pathlib import Path
  4. from supabase import Client
  5. from configs import dify_config
  6. from extensions.storage.base_storage import BaseStorage
  7. class SupabaseStorage(BaseStorage):
  8. """Implementation for supabase obs storage."""
  9. def __init__(self):
  10. super().__init__()
  11. if dify_config.SUPABASE_URL is None:
  12. raise ValueError("SUPABASE_URL is not set")
  13. if dify_config.SUPABASE_API_KEY is None:
  14. raise ValueError("SUPABASE_API_KEY is not set")
  15. if dify_config.SUPABASE_BUCKET_NAME is None:
  16. raise ValueError("SUPABASE_BUCKET_NAME is not set")
  17. self.bucket_name = dify_config.SUPABASE_BUCKET_NAME
  18. self.client = Client(supabase_url=dify_config.SUPABASE_URL, supabase_key=dify_config.SUPABASE_API_KEY)
  19. self.create_bucket(id=dify_config.SUPABASE_BUCKET_NAME, bucket_name=dify_config.SUPABASE_BUCKET_NAME)
  20. def create_bucket(self, id, bucket_name):
  21. if not self.bucket_exists():
  22. self.client.storage.create_bucket(id=id, name=bucket_name)
  23. def save(self, filename, data):
  24. self.client.storage.from_(self.bucket_name).upload(filename, data)
  25. def load_once(self, filename: str) -> bytes:
  26. content: bytes = self.client.storage.from_(self.bucket_name).download(filename)
  27. return content
  28. def load_stream(self, filename: str) -> Generator:
  29. result = self.client.storage.from_(self.bucket_name).download(filename)
  30. byte_stream = io.BytesIO(result)
  31. while chunk := byte_stream.read(4096): # Read in chunks of 4KB
  32. yield chunk
  33. def download(self, filename, target_filepath):
  34. result = self.client.storage.from_(self.bucket_name).download(filename)
  35. Path(target_filepath).write_bytes(result)
  36. def exists(self, filename):
  37. result = self.client.storage.from_(self.bucket_name).list(filename)
  38. if result.count() > 0:
  39. return True
  40. return False
  41. def delete(self, filename):
  42. self.client.storage.from_(self.bucket_name).remove(filename)
  43. def bucket_exists(self):
  44. buckets = self.client.storage.list_buckets()
  45. return any(bucket.name == self.bucket_name for bucket in buckets)