如何使查询参数在 fastapi 中采用两种类型的输入?
How to make query parameter take two types of inputs in fastapi?
我有这样的功能,
async def predict(static: str = Form(...), file: UploadFile = File(...)):
return something
我这里有两个参数,static和file,static是一个字符串,file是上传文件的buffer
现在,有没有一种方法可以将多种类型分配给一个参数,即我想让 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>
}
我有这样的功能,
async def predict(static: str = Form(...), file: UploadFile = File(...)):
return something
我这里有两个参数,static和file,static是一个字符串,file是上传文件的buffer
现在,有没有一种方法可以将多种类型分配给一个参数,即我想让 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>
}