我正在使用 pydantic 2.5.1 和 fastapi 0.103.2,当尝试使用 pydantic 和依赖注入验证输入时,我得到“输入应该是有效列表”
我尝试了这个Python代码:
class UserInput(BaseModel):
role_id: str
uids: list[str]
@validator('role_id')
def validate_role_id_length(cls, v):
if len(v) != 16:
raise ValueError("role_id must be 16 characters long")
return v
@validator('uids')
def validate_uid_length(cls, v):
for uid in v:
if len(uid) != 16:
raise ValueError("uids must be a list of 16 character strings")
return v
@approuter.post("/role/add_user/{role_id}")
async def handle_user_ids(data: UserInput = Depends()):
try:
return {"message": f"Successfully processed user IDs for role {data.role_id}"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
使用此 JSON 有效负载:
{
"uids": [
"asdfasdfasdfasdf",
"qwerqwerqwerqwer"
]
}
给我“输入应该是有效列表”错误。
当我添加另一个这样的列表时:
class UserInput(BaseModel):
role_id: str
uids: list[str]
asdf: list[str]
并在json负载上添加相应的“asdf”列表,它可以正常工作
据我了解,FastAPI 并不正式支持这种使用 Pydantic 模型的方式(
data: UserInput = Depends()
)。
FastAPI 路线图中支持非 Body 参数的 Pydantic 模型 (https://github.com/tiangolo/fastapi/issues/10370),但尚未实现:
支持 Query()、Form() 等 Pydantic 模型
不要将 Body 参数与其他参数混合,也不要使用 Depends()。这样一切都会按预期进行:
from pydantic import BaseModel, validator
from fastapi import FastAPI, HTTPException, Path
app = FastAPI()
class UserInput(BaseModel):
uids: list[str]
@validator('uids')
def validate_uid_length(cls, v):
for uid in v:
if len(uid) != 16:
raise ValueError("uids must be a list of 16 character strings")
return v
@app.post("/role/add_user/{role_id}")
async def handle_user_ids(data: UserInput, role_id: str = Path(min_length=16, max_length=16)):
try:
return {"message": f"Successfully processed user IDs for role {role_id}"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))