何为 Form 表单
相信你一定听过或者见过 HTMl
的 form
元素,这里所指的 Form
表单就是 FastApi 用来获取 HTML
中 form
元素的对象
一、安装必要的依赖
在开始之前,你需要安装 FastAPI 和相关依赖:
pip3 install fastapi uvicorn python-multipart
注意:python-multipart 是处理表单数据必需的库,因为 FastAPI 的表单解析依赖它
二、处理简单表单数据
下面是一个处理简单表单数据的完整示例:
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(
username: str = Form(...),
password: str = Form(...)
):
return {"username": username, "password_received": len(password)}
代码解释:
- 导入 Form:从
fastapi
导入Form
函数 - 定义路由:使用
@app.post
装饰器定义一个POST
请求处理函数 - 声明表单参数:在函数参数中使用
Form(...)
声明表单字段,... 表示该字段是必需的 - 处理数据:函数内部可以直接使用接收到的表单数据
三、处理复杂表单数据
1. 处理可选字段
@app.post("/register/")
async def register(
username: str = Form(...),
email: str = Form(...),
age: int | None = Form(None), # 可选字段
newsletter: bool = Form(False) # 带有默认值的可选字段
):
return {
"username": username,
"email": email,
"age": age,
"newsletter": newsletter
}
2. 处理列表字段
@app.post("/submit-tags/")
async def submit_tags(tags: list[str] = Form(...)):
return {"tags": tags}
3. 处理文件和表单混合数据
from fastapi import File, UploadFile
@app.post("/upload-profile/")
async def upload_profile(
name: str = Form(...),
avatar: UploadFile = File(...),
bio: str | None = Form(None)
):
# 处理文件和表单数据
return {
"name": name,
"avatar_filename": avatar.filename,
"bio": bio
}
四、表单数据验证
FastAPI 基于 Pydantic 提供了强大的数据验证功能:
from fastapi import HTTPException
from pydantic import EmailStr, PositiveInt
@app.post("/user/")
async def create_user(
name: str = Form(min_length=3, max_length=50),
email: EmailStr = Form(...), # 验证邮箱格式
age: PositiveInt = Form(...) # 验证正整数
):
# 数据已经经过验证
return {"name": name, "email": email, "age": age}
五、表单数据与请求体的区别
需要注意的是,表单数据和 JSON 请求体是不同的:
类型 | 编码方式 |
---|---|
表单数据 | application/x-www-form-urlencoded 或 multipart/form-data |
JSON 请求体 | application/json |
在 FastAPI 中,你不能在同一个请求中同时使用 Form 和 Body 来解析数据,因为它们使用不同的请求编码方式