Categories: FastAPI 教程

FastAPI教程 请求表单与文件

FastAPI 支持同时使用 File 和 Form 定义文件和表单字段。

说明

接收上传文件或表单数据,要预先安装 python-multipart

例如,pip install python-multipart。

导入 File 与 Form

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }

定义 File 与 Form 参数

创建文件和表单参数的方式与 Body 和 Query 一样:

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(
    file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
    return {
        "file_size": len(file),
        "token": token,
        "fileb_content_type": fileb.content_type,
    }

文件和表单字段作为表单数据上传与接收。

声明文件可以使用 bytes 或 UploadFile 。

警告

可在一个路径操作中声明多个 File 与 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码为 multipart/form-data,不是 application/json。

这不是 FastAPI 的问题,而是 HTTP 协议的规定。

小结

在同一个请求中接收数据和文件时,应同时使用 File 和 Form。

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

了解 ChatGPT 如何维护上下文

对话中的语境概念至关重要,因为…

4 天 ago

GenAI:如何通过快速压缩技术降低成本

在本文中,我们将探讨在开发早期…

1 周 ago

vue:页面注入js修改input值

一般会直接这样写: let z…

2 周 ago

聊聊vue3中的defineProps

在Vue 3中,defineP…

3 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

4 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

1 月 ago