Question

How to write Decorator or Wrapper over @validator in Pyndantic to print success msg after validator runs successfully

from pydantic import BaseModel, validator

def validator_decorator(message):
    def decorator(func):
        def wrapper(cls, v, values, config, field):
            # Call the original validator function
            result = func(cls, v, values, config, field)
            # Print the message after the validator runs
            print(message)
            return result
        return wrapper
    return decorator

class MyModel(BaseModel):
    name: str

    @validator_decorator("name validator")
    @validator('name')
    def name_must_contain_space(cls, v):
        if ' ' not in v:
            raise ValueError('must contain a space')
        return v.title()

# Testing the model
try:
    MyModel(name="John")
except ValueError as e:
    print(e)

model = MyModel(name="John Doe")
print(model.name)

The validator decorator is not working as expected and not printing any messages , help me how to write the wrapper to run the validator processed function.

 2  29  2
1 Jan 1970

Solution

 0

You can do something like the following:

from typing import Callable, Type

from pydantic.v1 import BaseModel, validator

def validator_decorator(field: str, message: str) -> Callable:
    def decorator(func: Callable) -> Callable:
        @validator(field)
        def wrapper(cls: Type[BaseModel], value: str) -> str:
            result = func(cls, value)
            print(message)
            return result
        return wrapper
    return decorator



class MyModel(BaseModel):
    name: str

    @validator_decorator(field="name", message="name validator")
    def name_must_contain_space(cls, value: str) -> str:
        if " " not in value:
            raise ValueError("Value mast contain space.")

        return value.title()
2024-07-19
Victor Egiazarian