简体   繁体   中英

How to validate maximum size of a Pydantic object with extra fields

I have a Pydantic object and while I want to allow extra fields not described in the schema, I want to enforce through validation the maximum size of the entire object. Suppose I have this definition:

from pydantic import Extra, BaseModel

class MyObject(BaseModel):
    x:int = 0

    class Config:
        extra = Extra.allow

I want MyObject(x=1, extra="value") to succeed but MyObject(x=1, extra="a"*1000) to throw a ValidationError .

Validation on the entire object can be enforced with @root_validator .

Assuming the maximum object size is measured as the size of its JSON serialization, the solution may look like this:

from pydantic import Extra, BaseModel, root_validator

MAX_SIZE = 1000

class MyObject(BaseModel):
    x:int = 0

    @root_validator(pre=True)
    def check_max_size(cls, values):
        if len(json.dumps(values)) > MAX_SIZE:
            raise ValueError('Object is too large')
        return values

    class Config:
        extra = Extra.allow

MyObject(x=1, extra="a"*1000) then raises

pydantic.error_wrappers.ValidationError: 1 validation error for MyObject
__root__
  Object is too large (type=value_error)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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