共计 1253 个字符,预计需要花费 4 分钟才能阅读完成。
pydantic
字段的默认值如何设置获取以后工夫
这种状况不要应用 default
,而要用 default_factory
对于这两种的区别阐明如下:
:param default: since this is replacing the field’s default, its first argument is used
to set the default, use ellipsis (``...``) to indicate the field is required
:param default_factory: callable that will be called when a default value is needed for this field
If both `default` and `default_factory` are set, an error is raised.
来看看谬误的例子,即通过 default
获取以后工夫:
from datetime import datetime, timezone
from pydantic import BaseModel, Field
from typing import Optional
import time
def get_utc_now_timestamp() -> datetime:
return datetime.utcnow().replace(tzinfo=timezone.utc)
class Struct(BaseModel):
releaseDate: Optional[datetime] = Field(default=get_utc_now_timestamp()
)
print(Struct().releaseDate)
time.sleep(1)
print(Struct().releaseDate)
能够看到两个工夫是一样的
2022-01-27 14:16:23.876755+00:00
2022-01-27 14:16:23.876755+00:00
再来看看 default_factory
:
from datetime import datetime, timezone
from pydantic import BaseModel, Field
from typing import Optional
import time
def get_utc_now_timestamp() -> datetime:
return datetime.utcnow().replace(tzinfo=timezone.utc)
class Struct(BaseModel):
releaseDate: Optional[datetime] = Field(default_factory=get_utc_now_timestamp)
print(Struct().releaseDate)
time.sleep(1)
print(Struct().releaseDate)
能够看到,两个工夫相距了 1
秒钟
2022-01-27 14:15:55.195409+00:00
2022-01-27 14:15:56.200775+00:00
正文完