Reputation: 574
I'm using json-schema to validate a schema. I wanted to customize the date-time type. So, redefined the type accordingly and extended the validator. But, it's not returning the error the way I'm looking for. My code:
BaseVal = jsonschema.Draft202012Validator
def date_time(checker, instance):
return datetime.strptime(instance, "%Y-%m-%dT%H:%M:%S")
timedatechecker = BaseVal.TYPE_CHECKER.redefine('date-time', date-time)
Validator = jsonschema.validators.extend(BaseVal, type_checker=timedatechecker)
errors = sorted(Validator(schema=schema).iter_errors(json), key=lambda e: e.path)
The errors variable currently contains all the errors during the schema validation, for example, id, age, etc., but not the error that occurs at datetime. I'm returning the errors list from the validation function. It returns True when there's no error, and the error list otherwise. When I POST a wrong datetime input from postman, it returns 500 Internal Server Error, and vscode shows this error message in terminal:
strptime raise ValueError("time data %r does not match format %r", %ValueError: time data '2015-01-35T05:05:05' does not match format '%Y-%m-%dT%H:%M:%S'
How can I make json-schema catch it, so I can use it from errors? Or any other workaround that'd achieve the same I'm trying to get. Thanks.
Upvotes: 0
Views: 694
Reputation: 53966
The format is called date-time
, not datetime
.
However, it would be much better for you to define a new format rather than redefine an existing one, as redefining formats breaks interoperability.
Upvotes: 2