搜索
首页后端开发Python教程如何在 FastAPI POST 请求中同时提交 JSON 和文件?

How to Submit Both JSON and Files in a FastAPI POST Request?

如何在 FastAPI POST 请求中同时添加文件和 JSON 正文?

在 FastAPI 中,您无法同时发送 JSON 数据和文件如果您将正文声明为 JSON,则为单个请求。相反,您需要使用 multipart/form-data 编码。以下是实现此目的的几种方法:

方法 1:使用文件和表单

# Assuming you have a DataConfiguration model for the JSON data
from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel

app = FastAPI()

class DataConfiguration(BaseModel):
    textColumnNames: list[str]
    idColumn: str

@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
               csvFile: UploadFile = File(...)):
    pass  # read requested id and text columns from csvFile

方法 2:使用 Pydantic 模型和依赖项

from fastapi import FastAPI, Form, File, UploadFile, Depends, Request
from pydantic import BaseModel
from typing import List, Optional, Dict
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class Base(BaseModel):
    name: str
    point: Optional[float] = None
    is_accepted: Optional[bool] = False

def validate_json_body(body: str = Form(...)):
    try:
        return Base.model_validate_json(body)
    except ValidationError as e:
        raise HTTPException(
            detail=jsonable_encoder(e.errors()),
            status_code=422,
        )

@app.post("/submit")
async def submit(base: Base = Depends(validate_json_body),
                  files: List[UploadFile] = File(...)):
    return {
        "JSON Payload": base,
        "Filenames": [file.filename for file in files],
    }

@app.get("/", response_class=HTMLResponse)
async def main(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

方法 3:将 JSON 传递为Body参数中的字符串

from fastapi import FastAPI, Form, UploadFile, File
from pydantic import BaseModel

class Base(BaseModel):
    name: str
    point: float
    is_accepted: bool

app = FastAPI()

@app.post("/submit")
async def submit(data: Base = Form(...), files: List[UploadFile] = File(...)):
    return {
        "JSON Payload": data,
        "Filenames": [file.filename for file in files],
    }

方法四:使用自定义类验证JSON

from fastapi import FastAPI, File, UploadFile, Request
from pydantic import BaseModel, model_validator
from typing import Optional, List
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import json

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class Base(BaseModel):
    name: str
    point: Optional[float] = None
    is_accepted: Optional[bool] = False

    @model_validator(mode='before')
    @classmethod
    def validate_to_json(cls, value):
        if isinstance(value, str):
            return cls(**json.loads(value))
        return value

@app.post("/submit")
async def submit(data: Base = Body(...), files: List[UploadFile] = File(...)):
    return {
        "JSON Payload": data,
        "Filenames": [file.filename for file in files],
    }

@app.get("/", response_class=HTMLResponse)
async def main(request: Request):
    return templates.TemplateResponse("index.html", context={"request": request})

注意:中方法1,您可以同时使用File 和Form 类,因为Form 是Body 的子类。但是,如果您在方法 1 中使用 Body(...) 而不是 Form(...),它将不起作用,因为 FastAPI 会期望 JSON 数据位于请求正文中,而不是表单数据。

以上是如何在 FastAPI POST 请求中同时提交 JSON 和文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用numpy创建多维数组?如何使用numpy创建多维数组?Apr 29, 2025 am 12:27 AM

使用NumPy创建多维数组可以通过以下步骤实现:1)使用numpy.array()函数创建数组,例如np.array([[1,2,3],[4,5,6]])创建2D数组;2)使用np.zeros(),np.ones(),np.random.random()等函数创建特定值填充的数组;3)理解数组的shape和size属性,确保子数组长度一致,避免错误;4)使用np.reshape()函数改变数组形状;5)注意内存使用,确保代码清晰高效。

说明Numpy阵列中'广播”的概念。说明Numpy阵列中'广播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增强可读性,和Boostsperformance.Shere'shore'showitworks:1)较小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

举一个场景的示例,其中使用Python列表比使用数组更合适。举一个场景的示例,其中使用Python列表比使用数组更合适。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python数组中访问元素?您如何在Python数组中访问元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解吗?如果是,为什么以及如果不是为什么?Python中有可能理解吗?如果是,为什么以及如果不是为什么?Apr 28, 2025 pm 04:34 PM

文章讨论了由于语法歧义而导致的Python中元组理解的不可能。建议使用tuple()与发电机表达式使用tuple()有效地创建元组。(159个字符)

Python中的模块和包装是什么?Python中的模块和包装是什么?Apr 28, 2025 pm 04:33 PM

本文解释了Python中的模块和包装,它们的差异和用法。模块是单个文件,而软件包是带有__init__.py文件的目录,在层次上组织相关模块。

Python中的Docstring是什么?Python中的Docstring是什么?Apr 28, 2025 pm 04:30 PM

文章讨论了Python中的Docstrings,其用法和收益。主要问题:Docstrings对于代码文档和可访问性的重要性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能