FastAPI 可选验证器
FastAPI Optional validator
我用 Student
模型写了一些 API,用于更新它 - 我使用另一个模型 StudentUpdateIn
。在 Student
模型上,我有验证器 ( gt = 15 )。但是如何将此验证器也应用于 StudentUpdateIn
?
我找到了使用 @validator
的方法,但我认为这不是我应该在我的代码中使用的方法。
最初选择的模式不正确....
class StudentUpdateIn(BaseModel):
first_name: Optional[str]
last_name: Optional[str]
age: Optional[int]
group: Optional[str]
@validator('age')
def greater_than(cls, v):
if not v > 15:
raise ValueError("Age must be greater than 15")
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
我很确定没有非 hacky 的方法可以做到这一点,但如果你不介意在代码中进行一些反省,这里是装饰器,它采用字段名称并在内部将 pydantic 字段标记为不需要(可选):
import inspect
def optional(*fields):
def dec(_cls):
for field in fields:
_cls.__fields__[field].required = False
return _cls
if fields and inspect.isclass(fields[0]) and issubclass(fields[0], BaseModel):
cls = fields[0]
fields = cls.__fields__
return dec(cls)
return dec
现在你可以用它来拥有单身class:
# you can specify optional fields - @optional("age", "group")
@optional
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
或继承
@optional
class StudentUpdateIn(StudentIn):
...
我用 Student
模型写了一些 API,用于更新它 - 我使用另一个模型 StudentUpdateIn
。在 Student
模型上,我有验证器 ( gt = 15 )。但是如何将此验证器也应用于 StudentUpdateIn
?
我找到了使用 @validator
的方法,但我认为这不是我应该在我的代码中使用的方法。
最初选择的模式不正确....
class StudentUpdateIn(BaseModel):
first_name: Optional[str]
last_name: Optional[str]
age: Optional[int]
group: Optional[str]
@validator('age')
def greater_than(cls, v):
if not v > 15:
raise ValueError("Age must be greater than 15")
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
我很确定没有非 hacky 的方法可以做到这一点,但如果你不介意在代码中进行一些反省,这里是装饰器,它采用字段名称并在内部将 pydantic 字段标记为不需要(可选):
import inspect
def optional(*fields):
def dec(_cls):
for field in fields:
_cls.__fields__[field].required = False
return _cls
if fields and inspect.isclass(fields[0]) and issubclass(fields[0], BaseModel):
cls = fields[0]
fields = cls.__fields__
return dec(cls)
return dec
现在你可以用它来拥有单身class:
# you can specify optional fields - @optional("age", "group")
@optional
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
或继承
@optional
class StudentUpdateIn(StudentIn):
...