简体   繁体   English

使用 pydantic (fastapi) 验证 json

[英]Validating json with pydantic (fastapi)

So I have a request that looks like this所以我有一个看起来像这样的请求

[
    {
        "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"
    }
]

and my code looks like this我的代码看起来像这样

@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"}

I'm basically looping through the array then inserting every object in the database, I'm looking for a solution that can validate every object with a pydantic model like this one:我基本上是循环遍历数组,然后将每个对象插入数据库中,我正在寻找一种可以使用像这样的 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

Or another solution better than mine, Thanks.或者比我更好的解决方案,谢谢。

In a FastAPI operation you can use a Pydantic model directly as a parameter.在 FastAPI 操作中,您可以直接使用 Pydantic 模型作为参数。 According to the FastAPI tutorial :根据FastAPI 教程

To declare a request body, you use Pydantic models with all their power and benefits.要声明请求正文,您可以使用Pydantic模型及其所有功能和优势。

[...] [...]

With just that Python type declaration, FastAPI will:仅使用该 Python 类型声明,FastAPI 将:

  • Read the body of the request as JSON.以 JSON 格式读取请求的正文。
  • Convert the corresponding types (if needed).转换相应的类型(如果需要)。
  • Validate the data验证数据
  • [...] [...]

Example:例子:

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

You can use the parse_obj_as Pydantic helper function to parse a list of dictionaries.您可以使用parse_obj_as Pydantic 辅助函数来解析字典列表。 So assuming item.json() returns a JSON string, you could do:所以假设item.json()返回一个 JSON 字符串,你可以这样做:

from pydantic import parse_obj_as

@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()
    try:
        validated_operations = parse_obj_as(List[EntretienModel], json.loads(operations))
        for i in validated_operations:
            i : EntretienModel
            new_operation = TableEntretien(**i)
            db.add(new_operation)
            db.commit()
            db.refresh(new_operation)
    except ValidationError as e:
        print(e)

This will validate each json record in item as a dict.这将验证item中的每个 json 记录作为字典。 From there you can proceed with inserting the records into your database.从那里您可以继续将记录插入数据库。 parse_obj_as documentation parse_obj_as 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM