Performance: Custom validators
Custom validators affect request validation speed and response time by adding extra processing during data parsing.
from pydantic import BaseModel, validator class User(BaseModel): age: int @validator('age') def check_age(cls, v): if v < 18: raise ValueError('Must be adult') return v
from pydantic import BaseModel, validator class User(BaseModel): age: int @validator('age') def check_age(cls, v): import time time.sleep(0.5) # Simulate slow validation if v < 18: raise ValueError('Must be adult') return v
| Pattern | Validation Time | Event Loop Blocking | Response Delay | Verdict |
|---|---|---|---|---|
| Blocking validator with sleep | High (500ms+) | Yes | High | [X] Bad |
| Simple synchronous validator | Low (milliseconds) | No | Low | [OK] Good |
@validator in FastAPI models?@validator@validator decorator is used to add custom validation logic to model fields in FastAPI.age?@validator decorator with the field name as a string argument.cls and value.age is set to 15?
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def check_age(cls, value):
if value < 18:
raise ValueError('Must be 18 or older')
return value
try:
user = User(age=15)
except Exception as e:
print(e)age is less than 18 and raises a ValueError if true.age=15 is less than 18, the validator raises the error.from pydantic import BaseModel, validator
class Product(BaseModel):
price: float
@validator('price')
def check_price(value):
if value <= 0:
raise ValueError('Price must be positive')
return valuecls as the first parameter, then value.check_price only has value, missing cls.cls parameter in validator method -> Option Bfrom pydantic import BaseModel, validator
class User(BaseModel):
username: str
@validator('username')
def validate_username(cls, value):
# Fill in validation logic here
passPass the test and this pattern moves unknown