Performance: Custom validation with validator decorator
This affects server response time and CPU usage during request validation.
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(1) # Simulate heavy computation if v < 18: raise ValueError('Must be adult') return v
| Pattern | CPU Usage | Blocking Time | Response Delay | Verdict |
|---|---|---|---|---|
| Heavy blocking validator | High | 1 second per request | High latency | [X] Bad |
| Simple synchronous validator | Low | Near zero | Minimal latency | [OK] Good |
@validator decorator in a Pydantic model within FastAPI?@validator@validator decorator is used inside Pydantic models to add custom validation logic for fields.email in a Pydantic model?@validator('field_name') with the field name as a string.@validator('email') correctly; others use wrong decorator names or syntax.age=15?
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def check_age(cls, v):
if v < 18:
raise ValueError('Must be at least 18')
return v
user = User(age=15)age is less than 18 and raises a ValueError if true.age=15 is less than 18, the validator raises the error with the message.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 the value.value, missing cls, causing a TypeError.cls parameter in validator method -> Option Bcls parameter in validator method [OK]username field to ensure it is at least 3 characters long and contains only letters and numbers. Which validator implementation correctly achieves this?Pass the test and this pattern moves unknown