Spaces:
Runtime error
Runtime error
File size: 3,461 Bytes
3c8d218 fbefffb 3c8d218 fbefffb 3c8d218 fbefffb 3c8d218 fbefffb 3c8d218 fbefffb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | import os
import shutil
from abc import ABC, abstractmethod
from typing import BinaryIO
class StorageProvider(ABC):
@abstractmethod
def save(self, file_content: BinaryIO, path: str) -> str:
"""Saves the file and returns the path/URL."""
return ""
@abstractmethod
def delete(self, path: str):
"""Deletes the file at the given path."""
pass
@abstractmethod
def get_full_path(self, path: str) -> str:
"""Returns the full accessible path or URL."""
return ""
class LocalStorageProvider(StorageProvider):
def __init__(self, base_dir: str = "backend/uploads"):
self.base_dir = base_dir
os.makedirs(self.base_dir, exist_ok=True)
def save(self, file_content: BinaryIO, relative_path: str) -> str:
full_path = os.path.join(self.base_dir, relative_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
# Ensure pointer is at the start
if hasattr(file_content, 'seek'):
file_content.seek(0)
with open(full_path, "wb") as buffer:
shutil.copyfileobj(file_content, buffer)
return full_path
def delete(self, relative_path: str):
full_path = os.path.join(self.base_dir, relative_path)
if os.path.exists(full_path):
os.remove(full_path)
def get_full_path(self, relative_path: str) -> str:
return os.path.join(self.base_dir, relative_path)
class SupabaseStorageProvider(StorageProvider):
def __init__(self, url: str, key: str, bucket: str = "assets"):
try:
from supabase import create_client, Client
self.client: Client = create_client(url, key)
self.bucket = bucket
except ImportError:
raise ImportError("Please install 'supabase' python package to use SupabaseStorageProvider")
def save(self, file_content: BinaryIO, relative_path: str) -> str:
# Supabase storage expects bytes or a file-like object
# We need to ensure the pointer is at the start if it was read before
if hasattr(file_content, 'seek'):
file_content.seek(0)
# Replace backslashes with forward slashes for cross-platform compatibility in Supabase
path = relative_path.replace("\\", "/")
# Binary content read
data = file_content.read()
# Upload to Supabase
try:
res = self.client.storage.from_(self.bucket).upload(
path=path,
file=data,
file_options={"upsert": "true"}
)
# Some versions of the client might return a dict with 'error'
if isinstance(res, dict) and res.get("error"):
raise Exception(f"Supabase upload error: {res['error']}")
except Exception as e:
print(f"[STORAGE] Supabase upload exception: {e}")
raise
# Returns the path in the bucket
return path
def delete(self, relative_path: str):
path = relative_path.replace("\\", "/")
self.client.storage.from_(self.bucket).remove([path])
def get_full_path(self, relative_path: str) -> str:
# For Supabase, we return the public URL or just the relative path
# depending on how it's used. Here we return the public URL.
res = self.client.storage.from_(self.bucket).get_public_url(relative_path.replace("\\", "/"))
return res
|