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