Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
72d27f1
1
Parent(s): 0f84c85
fix(products): finalize supabase storage implementation
Browse files- backend/app/api/products.py +44 -17
backend/app/api/products.py
CHANGED
|
@@ -218,23 +218,50 @@ async def upload_product_image(
|
|
| 218 |
- Cloudinary
|
| 219 |
- Supabase Storage
|
| 220 |
"""
|
| 221 |
-
#
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
if not file.content_type or not file.content_type.startswith("image/"):
|
| 225 |
raise HTTPException(
|
| 226 |
-
status_code=status.
|
| 227 |
-
detail="
|
| 228 |
)
|
| 229 |
|
| 230 |
-
#
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
- Cloudinary
|
| 219 |
- Supabase Storage
|
| 220 |
"""
|
| 221 |
+
# 1. Initialize Supabase
|
| 222 |
+
from app.core.supabase import supabase_client
|
| 223 |
+
if not supabase_client:
|
|
|
|
| 224 |
raise HTTPException(
|
| 225 |
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 226 |
+
detail="Supabase Storage not configured"
|
| 227 |
)
|
| 228 |
|
| 229 |
+
# 2. Sanitize filename & Rename to avoid collisions
|
| 230 |
+
# Format: {tenant_id}/{timestamp}_{safe_filename}
|
| 231 |
+
import re
|
| 232 |
+
import time
|
| 233 |
+
|
| 234 |
+
timestamp = int(time.time())
|
| 235 |
+
safe_filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', file.filename)
|
| 236 |
+
if len(safe_filename) > 50:
|
| 237 |
+
safe_filename = safe_filename[-50:]
|
| 238 |
+
|
| 239 |
+
# Tenant isolation folder
|
| 240 |
+
storage_path = f"{current_user.tenant_id}/{timestamp}_{safe_filename}"
|
| 241 |
+
|
| 242 |
+
# 3. Read file content
|
| 243 |
+
file_content = await file.read()
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
# 4. Upload to Supabase 'products' bucket
|
| 247 |
+
res = supabase_client.storage.from_("products").upload(
|
| 248 |
+
path=storage_path,
|
| 249 |
+
file=file_content,
|
| 250 |
+
file_options={"content-type": file.content_type}
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# 5. Get Public URL
|
| 254 |
+
public_url = supabase_client.storage.from_("products").get_public_url(storage_path)
|
| 255 |
+
|
| 256 |
+
return {
|
| 257 |
+
"url": public_url,
|
| 258 |
+
"filename": safe_filename,
|
| 259 |
+
"content_type": file.content_type
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
except Exception as e:
|
| 263 |
+
print(f"❌ Storage Upload Error: {e}")
|
| 264 |
+
raise HTTPException(
|
| 265 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 266 |
+
detail=f"Upload failed: {str(e)}"
|
| 267 |
+
)
|