关于python: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

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据