使用 pydantic (fastapi) 验证 json

-1 python pydantic fastapi

所以我有一个看起来像这样的请求

\n
[\n    {\n        "Code": "EVR-T-0dsfdsdf532",\n        "Agent": "pacman",\n        "Kilometrage": "60000",\n        "Operation": "Vidange",\n        "Piece_Consomable": "filtre \xc3\xa0 air",\n        "Quantit\xc3\xa9": 1,\n        "UnitPrice": "200.00",\n        "Montant": 200,\n        "Mainoeuvre": 100\n    },\n    {\n        "Code": "EVR-T-ddsdf53dfds2",\n        "Agent": "pacman",\n        "Kilometrage": "60000",\n        "Operation": "Pneumatique",\n        "Piece_Consomable": "(Autre) Uiop",\n        "Quantit\xc3\xa9": 1,\n        "UnitPrice": "200.00"\n    }\n]\n
Run Code Online (Sandbox Code Playgroud)\n

我的代码看起来像这样

\n
@app.post("/utilities/Entretien/submit", status_code=status.HTTP_200_OK)\nasync def create_item(item: Request, db: Session = Depends(get_db)):\n    operations = await item.json()\n    for i in operations:\n        i : EntretienModel\n        new_operation = TableEntretien(**i)\n        db.add(new_operation)\n        db.commit()\n        db.refresh(new_operation)\n    return {"ping": "pong"}\n
Run Code Online (Sandbox Code Playgroud)\n

我基本上是循环遍历数组,然后将每个对象插入数据库中,\n我正在寻找一种解决方案,可以使用如下所示的 pydantic 模型验证每个对象:

\n
class EntretienModel(BaseModel):\n    Code: str\n    Agent: str\n    Kilometrage: int\n    Operation: str\n    Piece_Consomable: str\n    Quantit\xc3\xa9: int\n    UnitPrice: float\n    Montant: int\n    Mainoeuvre: Union[int, None] = None\n
Run Code Online (Sandbox Code Playgroud)\n

或者其他比我更好的解决方案,谢谢。

\n

Her*_*cón 6

在 FastAPI 操作中,您可以直接使用 Pydantic 模型作为参数。根据FastAPI 教程

要声明请求主体,您可以使用Pydantic模型及其所有功能和优点。

[...]

通过 Python 类型声明,FastAPI 将:

  • 读取 JSON 格式的请求正文。
  • 转换相应的类型(如果需要)。
  • 验证数据
  • [...]

例子:

@app.post("/utilities/Entretien/submit", status_code=status.HTTP_200_OK)
async def create_item(operations: List[EntretienModel], db: Session = Depends(get_db)):
    ...
Run Code Online (Sandbox Code Playgroud)