我正在尝试创建一个 timedelta 的子类,它期望接收毫秒而不是秒,但它目前不起作用。
我是否违背了规律? Pydantic 是否有“正确”的方法来实现这一目标?或者我是否需要以某种方式告诉 Pydantic
MillisecondTimedelta
只是一个 timedelta
..
from datetime import timedelta
from pydantic import BaseModel
class MillisecondTimedelta(timedelta):
@classmethod
def __get_validators__(cls):
# timedelta expects seconds
yield lambda v: v / 1000
yield cls
class MyModel(BaseModel):
td: MillisecondTimedelta
data = {
"td": 7598040,
}
print(MyModel(**data))
结果:
Traceback (most recent call last):
File "main.py", line 14, in <module>
class MyModel(BaseModel):
File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__
File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer
File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__
File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare
File "pydantic/fields.py", line 541, in pydantic.fields.ModelField.populate_validators
File "pydantic/class_validators.py", line 255, in pydantic.class_validators.prep_validators
File "pydantic/class_validators.py", line 238, in pydantic.class_validators.make_generic_validator
File "/usr/lib/python3.8/inspect.py", line 3105, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "/usr/lib/python3.8/inspect.py", line 2854, in from_callable
return _signature_from_callable(obj, sigcls=cls,
File "/usr/lib/python3.8/inspect.py", line 2384, in _signature_from_callable
raise ValueError(
ValueError: no signature found for builtin type <class '__main__.MillisecondTimedelta'>
修改后的类报告如下;问题是 Pydantic 理解(对于 timedelta 字段) int 和浮点为秒 (源)。
class MillisecondTimedelta(timedelta):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
if any(isinstance(v, t) for t in (int, float)):
return cls(milliseconds=v)
现在一切都应该正常工作了。
>>> data = {"td": 1000}
>>> print(MyModel(**data))
td=MillisecondTimedelta(seconds=1)
编辑:如果没有自定义类和验证器,可以使用函数来编辑分配给类构造函数的值;需要装饰这个函数,如这里所示
class MyModel(BaseModel):
td: timedelta
@validator('td')
def convert_to_ms(cls, v):
return v / 1000
这个解决方案也有效:
>>> data = {"td": 3000}
>>> print(MyModel(**data))
td=datetime.timedelta(seconds=3)
啊哈,原来我需要改变两件事。
实际上从验证器返回一个
timedelta
,我正在返回cls
,这是我的自定义子类。
不要子类化
timedelta
from datetime import timedelta
from pydantic import BaseModel
class MillisecondTimedelta:
@classmethod
def __get_validators__(cls):
yield lambda v: timedelta(milliseconds=v)
class MyModel(BaseModel):
td: MillisecondTimedelta
data = {
"td": 7598040,
}
print(repr(MyModel(**data)))
MyModel(td=datetime.timedelta(seconds=7598, microseconds=40000))
在 pydantic v2 中你可以做这样的事情:
MillisecondTimedelta = Annotated[
timedelta,
BeforeValidator(lambda v: v / 1000 if isinstance(v, int) else v),
PlainSerializer(lambda v: int(v.total_seconds() * 1000), return_type=int),
]