Search code examples
pythonflasksupabasesupabase-database

How to upload file from python Flask web app to Supabase Storage


I want to be able to upload a file from Flask to Supabase Storage, but it only has documentation for the javascript api link to docs.

Also, I can't find any examples or any open source project that does that. Here it is my function to upload:

def upload_file(self):
    if 'file' not in request.files:
        flash('No file part')
        return redirect('/')
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return redirect('/')
    filename = secure_filename(file.filename)
    # upload to supabase storage
    return file.path

Solution

  • from storage3 import create_client
    
    url = "https://<your_supabase_id>.supabase.co/storage/v1"
    key = "<your api key>"
    headers = {"apiKey": key, "Authorization": f"Bearer {key}"}
    storage_client = create_client(url, headers, is_async=False)
    
    def upload_file(self):
        if 'file' not in request.files:
            flash('No file part')
            return redirect('/')
        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect('/')
        filename = secure_filename(file.filename)
    
        buckets = storage_client.list_buckets()
        bucket = buckets[0]
        return bucket.upload(filename, file)
    

    I didn't find official docs for python upload.
    Didn't test the code above so appreciate any feedback.
    I've based this on the github repo https://github.com/supabase-community/storage-py and the docs here https://supabase-community.github.io/storage-py/api/bucket.html