我想在 Cerberus 的 datetime 型別中驗證一個值大于或等于 01/01/1900 的欄位,但不能以這種方式作業:
from cerberus import Validator
from datetime import datetime
v = Validator()
schema = {
"birthdate": {
"type": "datetime",
"required": True,
"min": datetime(1900, 1, 1)
}
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}
print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False
任何人都可以幫助我嗎?
我將這個版本用于 Cerberus:Cerberus==1.3.4
uj5u.com熱心網友回復:
您的方法不是錯誤的,只是缺少一個決定性的組成部分——即考慮date-format。
試試這個:
from cerberus import Validator
from datetime import datetime
v = Validator()
to_date = lambda s: datetime.strptime(s, '%d/%m/%Y') # date-formatting
schema = {
"birthdate": {
"type": "datetime",
"required": True,
'coerce': to_date,
"min": datetime(1900, 1, 1)
}
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}
print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425383.html
