小编Rei*_*eis的帖子

FastApi - 接收正文请求中的对象列表

我需要创建一个端点,它可以接收以下 JSON 并识别其中包含的对象:

\n
{\xe2\x80\x8b\n  "data": [\n    {\xe2\x80\x8b\n      "start": "A", "end": "B", "distance": 6\n    }\xe2\x80\x8b,\n    {\xe2\x80\x8b\n      "start": "A", "end": "E", "distance": 4\n    }\xe2\x80\x8b\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我创建了一个模型来处理单个对象:

\n
class GraphBase(BaseModel):\n    start: str\n    end: str\n    distance: int\n
Run Code Online (Sandbox Code Playgroud)\n

有了它,我可以将其保存在数据库中。但现在我需要接收对象列表并将它们全部保存。\n我尝试执行以下操作:

\n
class GraphList(BaseModel):\n    data: Dict[str, List[GraphBase]]\n\n@app.post("/dummypath")\nasync def get_body(data: schemas.GraphList):\n    return data\n
Run Code Online (Sandbox Code Playgroud)\n

但我在 FastApi 上不断收到此错误:Error getting request body: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)并且在响应中收到此消息:

\n
{\n    "detail": "There was an error parsing the body"\n}\n …
Run Code Online (Sandbox Code Playgroud)

python json pydantic fastapi

8
推荐指数
1
解决办法
2万
查看次数

标签 统计

fastapi ×1

json ×1

pydantic ×1

python ×1