简体   繁体   English

如何使用 pydantic 生成严格的 json 模式?

[英]How to generate a strict json schema with pydantic?

I recently started to use pydandic to generate JSON schemas for validating data but I found the by default the generated schema does not complain about unknown keys inside my BaseModel.我最近开始使用 pydandic 生成 JSON 模式来验证数据,但我发现默认情况下生成的模式不会抱怨我的 BaseModel 中的未知键。

Example:例子:

class Query(BaseModel):
    id: str
    name: Optional[str]

The generated schema would pass validation even if the object has other attributes than the two one mentioned here.即使 object 具有此处提到的两个属性之外的其他属性,生成的模式也会通过验证。

How can I assure validation will fail if someone adds a "foo: bar" property?如果有人添加“foo:bar”属性,我如何确保验证失败?

You need to use a configuration on your model:您需要在 model 上使用配置:

from pydantic import BaseModel, Extra
class Query(BaseModel):
    id: str
    name: Optional[str]
    class Config:
        extra = Extra.forbid

It defaults to Extra.ignore , the other option is Extra.allow which adds any extra fields to the resulting object.它默认为Extra.ignore ,另一个选项是Extra.allow ,它将任何额外的字段添加到生成的 object 中。

You can also just use the strings "ignore" , "allow" , or "forbid"您也可以只使用字符串"ignore""allow""forbid"

Here are all the model config options you can use:以下是您可以使用的所有 model 配置选项:

https://pydantic-docs.helpmanual.io/usage/model_config/ https://pydantic-docs.helpmanual.io/usage/model_config/

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

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