pydantic 字段的默认值设置获取当前时间

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

你可能感兴趣的:(python)