我在 FastAPI 应用程序上收到以下错误。该错误与来自 PHP 数组的有效负载有关。我可以将 input_data 更改为另一种类型,我的挑战是输入看起来确实像常规字典,所以我不知道如何允许将此数组读取为字典。
async def post(input_data:dict):
{#908
+"detail": array:1 [
0 => {#890
+"type": "dict_type"
+"loc": array:1 [
0 => "body"
]
+"msg": "Input should be a valid dictionary"
+"input": "{"test":"No","fields":"X"}"
+"url": "https://errors.pydantic.dev/2.2/v/dict_type"
}
]
}
期望读取数组中包含的字典。
input_data 以字符串形式传入
"{"test":"No","fields":"X"}"
您可以使用
Pydantic
将其转换为字典。
import json
from pydantic import BaseModel, field_validator
class InputData(BaseModel):
input_data: dict
@field_validator("input_data", mode='before')
def sanitize_dict(cls, v):
return json.loads(v)
然后在你的 API 路径中
async def post(input_data:InputData):
```Your endpoint implementation here...```