-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor code into a common validator
- Loading branch information
Showing
2 changed files
with
56 additions
and
50 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# Copyright (c) IPython Development Team. | ||
# Distributed under the terms of the Modified BSD License. | ||
""" | ||
Common validator wrapper to provide a uniform usage of other schema validation | ||
libraries. | ||
""" | ||
|
||
from jsonschema import Draft4Validator as _JsonSchemaValidator | ||
from jsonschema import ValidationError | ||
|
||
try: | ||
import fastjsonschema | ||
from fastjsonschema import JsonSchemaException as _JsonSchemaException | ||
except ImportError: | ||
fastjsonschema = None | ||
_JsonSchemaException = ValidationError | ||
|
||
|
||
class Validator: | ||
""" | ||
Common validator wrapper to provide a uniform usage of other schema validation | ||
libraries. | ||
""" | ||
|
||
def __init__(self, schema): | ||
self._schema = schema | ||
|
||
# Validation libraries | ||
self._jsonschema = _JsonSchemaValidator(schema) # Default | ||
self._fastjsonschema_validate = fastjsonschema.compile(schema) if fastjsonschema else None | ||
|
||
def validate(self, data): | ||
""" | ||
Validate the schema of ``data``. | ||
Will use ``fastjsonschema`` if available. | ||
""" | ||
if fastjsonschema: | ||
try: | ||
self._fastjsonschema_validate(data) | ||
except _JsonSchemaException as e: | ||
raise ValidationError(e.message) | ||
else: | ||
self._jsonschema.validate(data) | ||
|
||
def iter_errors(self, data, schema=None): | ||
return self._jsonschema.iter_errors(data, schema) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters