Python使用Pydantic验证日期接受空字符串
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个错误是正常的。实际上,您要求一个日期或
none
,但是您通过一个字符串,当然是空的,但仍是一个字符串,因此,您不与该方案相对应。我看到的解决方案仅接受日期或一个空字符串,将是用联合编写模式,并按照以下方式编写您自己的验证器:
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: