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