django postgresql json字段模式验证

时间:2016-06-05 13:58:06

标签: json django postgresql jsonschema

我有一个带有JSONField的django模型(django.contrib.postgres.fields.JSONField) 有什么办法可以针对json模式文件验证模型数据吗?

(预保存)
my_field = JSONField(schema_file=my_schema_file)

这样的东西

4 个答案:

答案 0 :(得分:7)

为了做到这一点,我使用jsonschema编写了一个自定义验证器(Django 1.11,Python 3.6)。

<强> project/validators.py

from jsonschema import validate
from django.core.validators import BaseValidator

class JSONSchemaValidator(BaseValidator):
    def compare(self, a, b):
        return validate(a, b)

<强> project/app/models.py

from django.db import models
from django.contrib.postgres.fields import JSONField
from project.validators import JSONSchemaValidator

MY_JSON_FIELD_SCHEMA = {
    'type': 'object',
    'schema': 'http://json-schema.org/draft-07/schema#',
    'properties': {
        'my_key': {
            'type': 'string'
        }
    },
    'required': ['my_key']
}

class MyModel(models.Model):
    my_json_field = JSONField(
        default=dict,
        validators=[JSONSchemaValidator(limit_value=MY_JSON_FIELD_SCHEMA)]
    )

答案 1 :(得分:4)

这就是Model.clean()方法的用途(see docs)。例如:

class MyData(models.Model):
    some_json = JSONField()
    ...

    def clean(self):
        if not is_my_schema(self.some_json):
            raise ValidationError('Invalid schema.')

答案 2 :(得分:3)

您可以使用cerberus根据架构验证数据

from cerberus import Validator

schema = {'name': {'type': 'string'}}
v = Validator(schema)
data = {'name': 'john doe'}
v.validate(data)  # returns "True" (if passed)
v.errors  # this would return the error dict (or on empty dict in case of no errors)

它非常简单易用(也因为它的良好文档 - &gt;验证规则:http://docs.python-cerberus.org/en/stable/validation-rules.html

答案 3 :(得分:2)

我写了一个自定义JSONField,它扩展了models.JSONField,并使用jsonschema(Django 3.1,Python 3.7)验证了属性的值。

我之所以没有使用validators参数是出于一个原因:我想让用户动态定义架构。因此,我使用了schema参数,应该是:

  1. None(默认情况下):该字段的行为类似于其父类(不支持JSON模式验证)。
  2. 一个dict对象。此选项适用于小型架构定义(例如:{"type": "string"});
  3. 一个str对象,它描述包含模式代码的文件的路径。此选项适用于大型模式定义(以保留模型类定义代码的美感)。对于搜索,我使用所有启用的查找器:django.contrib.staticfiles.finders.find()
  4. 一个函数,该函数将模型实例作为参数,并返回模式作为dict对象。因此,您可以基于给定模型实例的状态构建模式。每次调用validate()时都会调用该函数。

myapp/models/fields.py

import json

from jsonschema import validators as json_validators
from jsonschema import exceptions as json_exceptions

from django.contrib.staticfiles import finders
from django.core import checks, exceptions
from django.db import models
from django.utils.functional import cached_property


class SchemaMode:
    STATIC = 'static'
    DYNAMIC = 'dynamic'


class JSONField(models.JSONField):
    """
    A models.JSONField subclass that supports the JSON schema validation.
    """
    def __init__(self, *args, schema=None, **kwargs):
        if schema is not None:
            if not(isinstance(schema, (bool, dict, str)) or callable(schema)):
                raise ValueError('The "schema" parameter must be bool, dict, str, or callable object.')
            self.validate = self._validate
        else:
            self.__dict__['schema_mode'] = False
        self.schema = schema
        super().__init__(*args, **kwargs)

    def check(self, **kwargs):
        errors = super().check(**kwargs)
        if self.schema_mode == SchemaMode.STATIC:
            errors.extend(self._check_static_schema(**kwargs))
        return errors

    def _check_static_schema(self, **kwargs):
        try:
            schema = self.get_schema()
        except (TypeError, OSError):
            return [
                checks.Error(
                    f"The file '{self.schema}' cannot be found.",
                    hint="Make sure that 'STATICFILES_DIRS' and 'STATICFILES_FINDERS' settings "
                         "are configured correctly.",
                    obj=self,
                    id='myapp.E001',
                )
            ]
        except json.JSONDecodeError:
            return [
                checks.Error(
                    f"The file '{self.schema}' contains an invalid JSON data.",
                    obj=self,
                    id='myapp.E002'
                )
            ]

        validator_cls = json_validators.validator_for(schema)

        try:
            validator_cls.check_schema(schema)
        except json_exceptions.SchemaError:
            return [
                checks.Error(
                    f"{schema} must be a valid JSON Schema.",
                    obj=self,
                    id='myapp.E003'
                )
            ]
        else:
            return []

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.schema is not None:
            kwargs['schema'] = self.schema
        return name, path, args, kwargs

    @cached_property
    def schema_mode(self):
        if callable(self.schema):
            return SchemaMode.DYNAMIC
        return SchemaMode.STATIC

    @cached_property
    def _get_schema(self):
        if callable(self.schema):
            return self.schema
        elif isinstance(self.schema, str):
            with open(finders.find(self.schema)) as fp:
                schema = json.load(fp)
        else:
            schema = self.schema
        return lambda obj: schema

    def get_schema(self, obj=None):
        """
        Return schema data for this field.
        """
        return self._get_schema(obj)

    def _validate(self, value, model_instance):
        super(models.JSONField, self).validate(value, model_instance)
        schema = self.get_schema(model_instance)
        try:
            json_validators.validate(value, schema)
        except json_exceptions.ValidationError as e:
            raise exceptions.ValidationError(e.message, code='invalid')

用法: myapp/models/__init__.py

def schema(instance):
    schema = {}
    # Here is your code that uses the other
    # instance's fields to create a schema.
    return schema


class JSONSchemaModel(models.Model):
    dynamic = JSONField(schema=schema, default=dict)
    from_dict = JSONField(schema={'type': 'object'}, default=dict)

    # A static file: myapp/static/myapp/schema.json
    from_file = JSONField(schema='myapp/schema.json', default=dict)