简体   繁体   English

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

[英]Python validate date using pydantic to accept empty string

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.我正在使用 pydantic 验证 AWS Lambda 中的数据,我有一个日期字段,可以接受有效日期或空字符串。

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.我尝试使用Union[datetime, str] ,它现在接受空字符串,但不再验证日期。

How can I make my field accept both empty string '' and validate the content if its a proper date ?如何让我的字段同时接受空字符串 '' 并验证内容是否是正确的日期?

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.实际上,您要求提供日期或None ,但是您传递了一个字符串,当然,它是空的,但仍然是一个字符串,因此,您不符合该方案。

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:我看到的仅接受日期或空字符串的解决方案是使用 Union 编写架构,并编写自己的验证器,如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM