You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python API上传文件至Supabase Storage并解决桶列表为空问题

解决Supabase Storage Python客户端list_buckets返回空及PNG上传方法

一、修复list_buckets返回空的问题

你的代码核心问题是客户端初始化方式错误,Supabase Python SDK的create_client无需手动构造headers,直接传入项目URL和API key即可,SDK会自动处理认证逻辑。

正确初始化步骤

先确保安装官方SDK:

pip install supabase

替换你的初始化代码:

from supabase import create_client, Client

# 替换为你的Supabase项目URL和API key
supabase_url = "你的Supabase项目URL"
supabase_key = get_settings().supabase_key

# 初始化Supabase客户端
supabase: Client = create_client(supabase_url, supabase_key)
# 获取存储客户端实例
storage_client = supabase.storage

# 重新尝试列出桶
print(storage_client.list_buckets())

额外排查点

  • 确认Supabase控制台中确实已创建桶,且桶名称无拼写错误
  • 检查API key类型:若用anon key,需确保桶的List buckets权限政策允许匿名用户访问;service role key拥有全权限,适合后端操作场景

二、PNG文件上传至Supabase Storage的完整流程

1. 基础上传示例

# 配置参数
bucket_name = "你的桶名称"
local_png_path = "./test.png"  # 本地PNG文件路径
storage_destination = "images/test.png"  # 存储中的目标路径,可自定义

# 读取文件并上传
with open(local_png_path, "rb") as png_file:
    upload_result = storage_client.from_(bucket_name).upload(
        path=storage_destination,
        file=png_file,
        file_options={"content-type": "image/png"}  # 指定文件MIME类型
    )
    print(upload_result)

# 获取公共访问URL(需桶已开启Public access权限)
public_url = storage_client.from_(bucket_name).get_public_url(storage_destination)
print("公共访问URL:", public_url)

2. 权限注意事项

  • 若需公开访问上传的PNG,需在Supabase控制台的桶设置中开启Public access
  • 若仅允许授权用户访问,可通过Supabase的Row Level Security (RLS) 配置桶的访问政策

三、核心操作参考

Supabase Python存储客户端常用方法:

  • list_buckets(): 列出项目下所有存储桶
  • from_(bucket_name): 指定要操作的目标桶
  • upload(path, file, file_options): 上传文件,支持文件对象或字节流
  • download(path): 下载指定路径的文件,返回字节数据
  • get_public_url(path): 获取文件的公共访问链接
  • remove(paths): 批量删除指定路径的文件

内容的提问来源于stack exchange,提问作者Tik Tok Collecter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:10:28