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

FastAPI混合表单与文件上传中如何设置可选Form字段?

解决FastAPI混合表单字段与文件上传中可选字段的问题

要将表单字段设为可选,核心是在Form()中显式指定default=None,而非仅通过类型声明Union[str, None]或Optional[str]标记。以下是正确实现方式:

正确写法1:Union + Form(default=None)

@router.post("/upload")
async def upload_contents(
    an_int: Annotated[int, Form()],
    a_string: Annotated[Union[str, None], Form(default=None)], 
    some_files: Annotated[list[UploadFile], File()]
):
    # 业务处理逻辑
    return {"an_int": an_int, "a_string": a_string, "uploaded_files": len(some_files)}

正确写法2:Optional + Form(default=None)

from typing import Optional

@router.post("/upload")
async def upload_contents(
    an_int: Annotated[int, Form()],
    a_string: Annotated[Optional[str], Form(default=None)], 
    some_files: Annotated[list[UploadFile], File()]
):
    # 业务处理逻辑
    return {"an_int": an_int, "a_string": a_string, "uploaded_files": len(some_files)}

原写法无效的原因

  • 写法一仅声明了Union[str, None]类型,但未给Form()设置默认值。FastAPI默认将表单字段视为必填项,因此仍会强制要求客户端提供a_string。
  • 写法二存在语法错误(括号配对错误),且同样未设置default=None,即便修正语法,也无法将字段设为可选。

FastAPI中,表单字段的必填性由Form()的default参数直接控制——只要显式设置default=None,无论类型是Union还是Optional,该字段都会变为可选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:23