当制作一个使用列表字段依赖注入的应用程序时,参数会自动转到 SwaggerUI 中的请求体:
from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List
class QueryParams(BaseModel):
name: str = Field(...)
ages: List[int] = Field([])
app = FastAPI()
@app.get("/test")
def test(query: QueryParams = Depends()):
return "hi"
uvicorn.run(app)
这意味着我无法在 swagger UI 中测试它。即使我改字段查询,还是不行:
from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List
class QueryParams(BaseModel):
name: str = Field(...)
ages: List[int] = Query([]) # <-- Query
app = FastAPI()
@app.get("/test")
def test(query: QueryParams = Depends()):
return "hi"
uvicorn.run(app)
如果我把它放在路由函数中,它就起作用了:
from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List
class QueryParams(BaseModel):
name: str = Field(...)
app = FastAPI()
@app.get("/test")
def test(query: QueryParams = Depends(), ages: List[int] = Query([])):
return "hi"
uvicorn.run(app)
如何让 swagger UI 识别具有依赖注入的基本模型中的列表查询字段?
如this answer中所述,不能在 Pydantic 模型中使用
List
字段并期望它是 query
参数。这样做的方法是在一个单独的依赖类中实现您的查询参数解析,如下所示:
class QueryParams:
def __init__(
self,
name: str,
ages: List[int] = Query(...)
):
self.name = name
self.ages = ages
@app.get("/test")
def test(query: QueryParams = Depends()):
return "hi"
@dataclass
装饰器重写,如下所示:
from dataclasses import dataclass
@dataclass
class QueryParams:
name: str
ages: List[int] = Query(...)
@app.get("/test")
def test(query: QueryParams = Depends()):
return "hi"
可以将
Query()
包装在 Field()
中,这样他们就可以在 Pydantic 模型中定义一个 List
字段作为查询参数。可以在this answer中找到一个工作示例。