FastApi / supabase_service.py
Soumik555's picture
use supabase
f79ab83
raw
history blame
1.54 kB
import os
from supabase import create_client, Client
# Replace with your Supabase URL and API key
SUPABASE_URL: str = os.getenv("SUPABASE_URL")
SUPABASE_KEY: str = os.getenv("SUPABASE_KEY")
# Initialize the Supabase client
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
# Define the bucket name (you can create one in the Supabase Storage section)
BUCKET_NAME = "csvcharts"
async def upload_image_to_supabase(file_path: str, file_name: str) -> str:
"""
Uploads an image to Supabase Storage and returns the public URL.
:param file_path: Path to the image file on your local machine.
:param file_name: Name to save the file as in Supabase Storage.
:return: Public URL of the uploaded image.
"""
# Check if the file exists
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
# Read the file in binary mode
with open(file_path, "rb") as f:
file_data = f.read()
# Upload the file to Supabase Storage
try:
res = supabase.storage.from_(BUCKET_NAME).upload(file_name, file_data)
# print("Upload response:", res) # Debugging: Print the response
except Exception as e:
print(f"Error uploading file: {e}")
raise Exception(f"Failed to upload file: {e}")
# Get the public URL of the uploaded file
public_url = supabase.storage.from_(BUCKET_NAME).get_public_url(file_name)
# print("Public URL:", public_url) # Debugging: Print the public URL
return public_url