Python使用Pydantic验证日期接受空字符串

发布于 2025-02-04 02:58:30 字数 549 浏览 2 评论 0原文

我正在使用pydantic验证AWS lambda中的数据,我有一个可以接受有效日期或空字符串的日期字段。

当我将一个空字符串传递到该字段“日期”时,它不起作用,并且会收到以下错误:

pydantic.error_wrappers.ValidationError: 1 validation error for EmployeeInput
date
  invalid datetime format (type=value_error.datetime)

这就是我定义模型的方式:

class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Optional[datetime] = get_date_now()

我尝试使用union [dateTime,str] ,它现在接受空字符串,但不再验证日期。

如果其适当的日期,我该如何使我的字段同时接受空字符串''并验证内容?

I'm using pydantic to validate data in AWS Lambda, I have a field for date that can accept either a valid date or empty string.

When I pass an empty string to that field 'date', it does not work and I get the following error :

pydantic.error_wrappers.ValidationError: 1 validation error for EmployeeInput
date
  invalid datetime format (type=value_error.datetime)

This is how I defined the model :

class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Optional[datetime] = get_date_now()

I have tried to use Union[datetime, str], it is now accepting empty string but does not validate date anymore.

How can I make my field accept both empty string '' and validate the content if its a proper date ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天暗了我发光 2025-02-11 02:58:30

您的第一个错误是正常的。实际上,您要求一个日期或none,但是您通过一个字符串,当然是空的,但仍是一个字符串,因此,您不与该方案相对应。

我看到的解决方案仅接受日期或一个空字符串,将是用联合编写模式,并按照以下方式编写您自己的验证器:

def date_validator(date):
    if not isinstance(date, datetime) and len(date) > 0:
        raise ValueError(
            "date is not an empty string and not a valid date")
    return date


class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Union[datetime, str] = get_date_now()

    _date_validator = validator(
        'date', allow_reuse=True)(date_validator)

Your first error is normal. Indeed, you ask for either a date, or None, but you pass a string, certainly, empty but a string nevertheless, so, you do not correspond to the scheme.

The solution I see to accept a date or an empty string only, would be to write your schema with an Union, and write your own validator as follows:

def date_validator(date):
    if not isinstance(date, datetime) and len(date) > 0:
        raise ValueError(
            "date is not an empty string and not a valid date")
    return date


class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Union[datetime, str] = get_date_now()

    _date_validator = validator(
        'date', allow_reuse=True)(date_validator)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文