Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

313
Visualizações
Pydantic validator does not work as expected

I have recently found the power of Pydantic validators and proceeded to uses them in one of my personal projects.

However, I've encountered a problem: the failure of one validator does not stop the execution of the following validators, resulting in an Exception.

class Field(BaseModel):
    name: constr(min_length=1, max_length=32)
    type: constr(min_length=1, max_length=32)
    length: Optional[int]
    nullable: bool


class Unique(BaseModel):
    name: constr(min_length=1, max_length=32)
    unique_fields: List[constr(min_length=1, max_length=32)]


class Resource(BaseModel):
    name: constr(min_length=1, max_length=32)
    table_name: constr(min_length=1, max_length=32)
    fields: List[Field]
    primary_key: constr(min_length=1, max_length=32)
    uniques: Optional[List[Unique]]

    @validator('name')
    def resource_name_must_be_pure_string(cls, v):
        if not v.isalpha():
            raise ValueError(ONLY_ALPHA_ERR.format("Resource name"))
        return v

    @validator('table_name')
    def table_name_must_be_pure_string(cls, v):
        if not v.isalpha():
            raise ValueError(ONLY_ALPHA_ERR.format("Table name"))
        return v

    @validator('fields', pre=True)
    def field_name_must_be_pure_string(cls, v):
        fieldnames = [field["name"] for field in v]
        print(fieldnames)
        for fieldname in fieldnames:
            if not fieldname.replace('_', '').isalpha():
                print('was here')
                raise ValueError("A field's name can only contain alphabetic characters and '_'.")
        return v

    @validator('primary_key')
    def primary_key_must_be_in_fields(cls, v, values):
        fieldnames = [field.name for field in values["fields"]]

        if v not in fieldnames:
            raise ValueError(f"Primary key `{v}` should be one of the input fields.")
        return v

The method field_name_must_be_pure_string prints "was here", therefore the ValueError exception should have been raised, but the execution proceeds to the next validator, which would be primary_key_must_be_in_fields, that fails because the preceding list of fields was invalid.

What would be the solution to this corner case?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Late answer, but managed to avoid getting a crash by using the following:

@validator('primary_key')
def primary_key_must_be_in_fields(cls, v, values):
    if "fields" not in values:
        return

    fieldnames = [field.name for field in values["fields"]]

    if v not in fieldnames:
        raise ValueError(f"Primary key `{v}` should be one of the input fields.")
    return v

It took a while to realise that Pydantic will do all validations and will not stop at first exception.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda