supabase_storage.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import io
  2. from collections.abc import Generator
  3. from pathlib import Path
  4. from flask import Flask
  5. from supabase import Client
  6. from extensions.storage.base_storage import BaseStorage
  7. class SupabaseStorage(BaseStorage):
  8. """Implementation for supabase obs storage."""
  9. def __init__(self, app: Flask):
  10. super().__init__(app)
  11. app_config = self.app.config
  12. self.bucket_name = app_config.get("SUPABASE_BUCKET_NAME")
  13. self.client = Client(
  14. supabase_url=app_config.get("SUPABASE_URL"), supabase_key=app_config.get("SUPABASE_API_KEY")
  15. )
  16. self.create_bucket(
  17. id=app_config.get("SUPABASE_BUCKET_NAME"), bucket_name=app_config.get("SUPABASE_BUCKET_NAME")
  18. )
  19. def create_bucket(self, id, bucket_name):
  20. if not self.bucket_exists():
  21. self.client.storage.create_bucket(id=id, name=bucket_name)
  22. def save(self, filename, data):
  23. self.client.storage.from_(self.bucket_name).upload(filename, data)
  24. def load_once(self, filename: str) -> bytes:
  25. content = self.client.storage.from_(self.bucket_name).download(filename)
  26. return content
  27. def load_stream(self, filename: str) -> Generator:
  28. def generate(filename: str = filename) -> 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. return generate()
  34. def download(self, filename, target_filepath):
  35. result = self.client.storage.from_(self.bucket_name).download(filename)
  36. Path(result).write_bytes(result)
  37. def exists(self, filename):
  38. result = self.client.storage.from_(self.bucket_name).list(filename)
  39. if result.count() > 0:
  40. return True
  41. return False
  42. def delete(self, filename):
  43. self.client.storage.from_(self.bucket_name).remove(filename)
  44. def bucket_exists(self):
  45. buckets = self.client.storage.list_buckets()
  46. return any(bucket.name == self.bucket_name for bucket in buckets)