FastAPI 用 Form() 怎样读取 HTML 表单?
查看完整题解
参考回答
直接回答
用 Annotated[str, Form()] 等声明表单字段,并安装 python-multipart。客户端按表单编码提交,FastAPI 从表单取字段,完成类型校验。
讲清原理
普通表单常用 URL 编码,有文件时多用 multipart。一个请求的正文类型不能同时既是表单又是普通 JSON,设计接口时应选定约定。
例子与易错点
示例发送表单数据并检查字段;省略必填项会得到校验错误。如果接口还要收文件,可以把表单字段放在同一 multipart 请求中。
from typing import Annotated
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/preferences")
def preferences(label: Annotated[str, Form(min_length=1, max_length=30)]):
return {"label": label}
with TestClient(app) as client:
accepted = client.post("/preferences", data={"label": "Coffee"})
assert accepted.json() == {"label": "Coffee"}
assert client.post("/preferences", data={}).status_code == 422
print(accepted.json()["label"])
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。