-
-
Save mrroot5/4a7413bc335c67db7ee3c0448d3cff31 to your computer and use it in GitHub Desktop.
Django json schema validator
This file contains hidden or 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
import json | |
import os | |
from django.contrib.postgres.fields import JSONField | |
from django.core.exceptions import ValidationError | |
from django.utils.deconstruct import deconstructible | |
from jsonschema import validate, exceptions as jsonschema_exceptions | |
@deconstructible | |
class JSONSchemaValidator(JSONField): | |
def __init__(self, *args , **kwargs): | |
schema = kwargs.pop('schema', None) | |
if not schema: | |
raise ValueError('Schema is required') | |
if not isinstance(schema, str): | |
raise TypeError('Schema must be a path string, ex: "schemas/media_effects_jsonschema.json"') | |
self.schema = schema | |
super().__init__(*args, **kwargs) | |
@property | |
def _schema_data(self): | |
dirname = os.path.dirname(os.path.realpath(__file__)) | |
p = os.path.join(dirname, self.schema) | |
with open(p, 'r') as read_file: | |
return json.loads(read_file.read()) | |
def __call__(self, value): | |
try: | |
status = validate(json.loads(value), self._schema_data) | |
except jsonschema_exceptions.ValidationError as err: | |
error_msg = '{} {}.'.format( | |
self.error_messages.get('invalid', str(err)), | |
'Please check jsonschema' | |
) | |
raise ValidationError(error_msg) | |
except ValueError as err: | |
raise ValidationError('Field should be a valid json') | |
return status |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment