python - 如何使fastapi中的查询参数接受两种类型的输入?

标签 python python-3.x fastapi

我有一个这样的功能,

async def predict(static: str = Form(...), file: UploadFile = File(...)):
    return something

这里有两个参数,static和file,static是一个字符串,file是上传文件的缓冲区。

现在,有没有一种方法可以为一个参数分配多种类型,即我想让 file 参数接受上传文件或仅接受字符串

最佳答案

使用Union类型注释

from fastapi import FastAPI, UploadFile, Form, File
<b>from typing import Union</b>

app = FastAPI()


@app.post(path="/")
async def predict(
        static: str = Form(...),
        <b>file: Union[UploadFile, str] = File(...)</b>
):
    return {
        "received_static": static,
        <b>"received_file": file if isinstance(file, str) else file.filename</b>
    }

据我所知,OpenAPI 架构不支持此配置,因为它不支持多种类型。因此,最好定义多个参数来以不同的方式处理事情。另外,恕我直言,这是更好的方法

from fastapi import FastAPI, UploadFile, Form, File

app = FastAPI()


@app.post(path="/")
async def predict(
        static: str = Form(...),
        <b>file: UploadFile = File(None),  # making optional
        file_str: str = Form(None)  # making optional</b>
):
    return {
        "received_static": static,
        <b>"received_file": file.filename if file else None,
        "received_file_str": file_str if file_str else ''</b>
    }

关于python - 如何使fastapi中的查询参数接受两种类型的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64496283/

相关文章:

python - 为什么提高精度会使这个程序更快?

python - FastAPI 应用程序在本地运行但不在 Docker 容器中

python - FastAPI 等效于 Flask 的 request.form,用于不可知的表单

python - 将 numpy 函数转换为 theano

python - PyQt5:通过单击 QPushButton 画一条线

django - django/tastypie 上的 PendingDeprecationWarning

python - cv2.imshow 失败 : Fontconfig error: failed reading config file

python - 如何在fastapi响应中包含非pydantic类?

python - django 的 request.META.get ('wsgi.url_scheme' ) 返回 http 而不是 https

python - 在python中使用某些顺序规则合并两个列表