0%

FastAPI自学教程(24) - 请求表单与文件混合处理

1. 表单与文件混合处理基础

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI, Form, File, UploadFile

app = FastAPI()

@app.post("/profile/")
async def create_profile(
name: str = Form(...),
age: int = Form(...),
avatar: UploadFile = File(...)
):
return {
"name": name,
"age": age,
"avatar_size": len(await avatar.read())
}
  • 必须安装 python-multipart 依赖:pip install python-multipart
  • 使用 Form() 声明表单字段,File() 声明文件字段
  • 请求编码类型自动识别为 multipart/form-data
  • 支持同时接收多个表单字段和多个文件字段

2. 数据验证与参数配置

1
2
3
4
5
6
7
8
@app.post("/upload/")
async def secure_upload(
username: str = Form(min_length=4, example="user123"),
file: UploadFile = File(..., max_size=1024*1024)
):
if not file.filename.endswith(".pdf"):
raise HTTPException(400, "仅支持PDF文件")
return {"user": username, "file_type": file.content_type}
  • 支持字段级验证:min_length/max_length/regex
  • 文件参数支持 max_size 限制体积(单位:字节)
  • 自定义验证逻辑(如文件后缀校验)

3. 模型化混合处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from pydantic import BaseModel
from typing import Annotated

class ProfileForm(BaseModel):
name: str
bio: str | None = None

@app.post("/model-profile/")
async def model_profile(
form: Annotated[ProfileForm, Form()],
photos: list[UploadFile] = File(...)
):
return {
"profile": form.dict(),
"photo_count": len(photos)
}
  • 使用 Pydantic 模型批量管理表单字段(FastAPI 0.115.0+)
  • 支持 List[UploadFile] 接收多个文件
  • 自动数据转换与验证,错误返回 422 状态码

4. 高级文件处理技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import aiofiles

@app.post("/store-file/")
async def store_file(
description: str = Form(...),
file: UploadFile = File(...)
):
async with aiofiles.open(file.filename, "wb") as buffer:
await buffer.write(await file.read())

return {
"saved_as": file.filename,
"description": description,
"size": file.size
}
  • 使用 aiofiles 异步存储文件避免阻塞
  • UploadFile 对象特性:
    • .filename 获取原始文件名
    • .size 获取文件体积
    • .content_type 获取 MIME 类型
  • 支持流式处理大文件(自动使用磁盘缓存)

5. 注意事项

  1. 依赖管理:必须安装 python-multipart,否则无法处理表单数据
  2. 内存优化:超过 1MB 的文件建议使用 UploadFile 代替 bytes
  3. 安全实践
    • 校验文件类型(后缀名 + 魔数校验)
    • 限制最大文件体积
  4. 生产部署
    • 使用 Nginx 配置 client_max_body_size
    • 启用 HTTPS 保障数据传输安全
  5. 文档交互:Swagger UI 自动生成测试界面,需手动选择文件