我有一个像这样的请求
[
{
"Code": "EVR-T-0dsfdsdf532",
"Agent": "pacman",
"Kilometrage": "60000",
"Operation": "Vidange",
"Piece_Consomable": "filtre à air",
"Quantité": 1,
"UnitPrice": "200.00",
"Montant": 200,
"Mainoeuvre": 100
},
{
"Code": "EVR-T-ddsdf53dfds2",
"Agent": "pacman",
"Kilometrage": "60000",
"Operation": "Pneumatique",
"Piece_Consomable": "(Autre) Uiop",
"Quantité": 1,
"UnitPrice": "200.00"
}
]
我的代码是这样的
@app.post("/utilities/Entretien/submit", status_code=status.HTTP_200_OK)
async def create_item(item: Request, db: Session = Depends(get_db)):
operations = await item.json()
for i in operations:
i : EntretienModel
new_operation = TableEntretien(**i)
db.add(new_operation)
db.commit()
db.refresh(new_operation)
return {"ping": "pong"}
我基本上是遍历数组然后插入数据库中的每个对象,我正在寻找一个解决方案,可以验证每个对象与pydantic模型像这样:
class EntretienModel(BaseModel):
Code: str
Agent: str
Kilometrage: int
Operation: str
Piece_Consomable: str
Quantité: int
UnitPrice: float
Montant: int
Mainoeuvre: Union[int, None] = None
或者另一个比我的更好的解决方案,谢谢。
在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)):
...