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

Supabase Storage Python无法执行Upsert及捕获异常问题求助

问题解决思路

1. Upsert参数不生效的原因及修复

Supabase Python SDK中,upsert参数需要传入布尔值类型(True/False),而非字符串"true"。你当前代码里的字符串参数无法被SDK正确识别,因此未触发覆盖已存在文件的逻辑,导致抛出资源已存在的异常。

修正后的file_options应该是:

file_options={"content-type": "image/jpeg", "cache-control": "3600", "upsert": True}

另外,建议确认你的supabase-py SDK是最新版本,旧版本可能存在参数兼容问题,执行升级命令:

pip install --upgrade supabase

2. 异常未被捕获的原因及修复

你的except块中判断的是错误信息是否包含"Duplicate",但实际抛出的异常信息是"The resource already exists",导致条件不成立,进而重新抛出了异常,看起来像是未被捕获。

有两种修复方式:

方式一:直接捕获StorageException

先导入对应的异常类,精准捕获:

from supabase.lib.client_options import StorageException

try:             
    result = supabase.storage.from_(STORAGE_BUCKET).upload(
        file=f, 
        path=f"{storagepath}/{basename}", 
        file_options={"content-type": "image/jpeg", "cache-control": "3600", "upsert": True}
    )
 except StorageException as err:
      strErr = str(err)
      if "The resource already exists" not in strErr:
          raise  # 只重新抛出非重复资源的异常
 except Exception as err:
      # 处理其他类型的异常
      raise

方式二:修改字符串判断条件

如果不想导入特定异常类,直接调整判断的关键词:

try:             
    result = supabase.storage.from_(STORAGE_BUCKET).upload(
        file=f, 
        path=f"{storagepath}/{basename}", 
        file_options={"content-type": "image/jpeg", "cache-control": "3600", "upsert": True}
    )
 except Exception as err:
      strErr = str(err)
      if "The resource already exists" not in strErr:
          raise Exception from err

额外提示

拼接路径时建议使用f"{storagepath}/{basename}",比字符串相加更简洁易读,也能避免路径分隔符拼接错误。

内容的提问来源于stack exchange,提问作者Lukasz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:48:12