我有一个这样的功能,
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/