django REST框架,验证json数据

时间:2018-09-04 13:15:58

标签: json django django-rest-framework

服务器带有json格式:

{
    "type": "string",
    "object": {
        "lead_id": int,
        "form_name": "string",
        "answers": [
            {
                "lead_id": int,
                "key": "string",
            }
            ...
        ]
    },
    "group_id": int,
    "secret": "string"
}

如何使用django REST框架来验证此json?

ru版本

3 个答案:

答案 0 :(得分:1)

您可以像这样使用django rest框架编写自己的验证器,

class MultipleOf(object):
   def __init__(self, base):
       self.base = base

   def __call__(self, value):
       if value % self.base != 0:
           message = 'This field must be a multiple of %d.' % self.base
           raise serializers.ValidationError(message)

您可以找到更多详细信息here

希望这会有所帮助!

答案 1 :(得分:1)

class AnswersSerializer(serializers.Serializer):
    lead_id = serializers.IntegerField(required=True)
    key = serializers.CharField(max_length=100)

class ObjectSerializer(serializers.Serializer):
    lead_id = serializers.IntegerField(required=True)
    form_name = serializers.CharField(max_length=100)
    answers = serializers.ListField(child=AnswersSerializer())

class UpdateGroup(serializers.Serializer):
    group_id = serializers.IntegerField(required=True)
    type = serializers.CharField(max_length=100)
    secret = serializers.CharField(max_length=100)
    object = serializers.DictField(child=, default={})

答案 2 :(得分:0)

示例:

# serializers.py
from rest_framework import serializers


class VkObjectSerializer(serializers.Serializer):
    """
    is 'object'
    """
    lead_id = serializers.IntegerField()
    group_id = serializers.IntegerField()
    user_id = serializers.IntegerField()
    form_id = serializers.IntegerField()


class VkBaseSerializer(serializers.Serializer):
    """
    Base serializer 
    """
    type = serializers.CharField(max_length=200)

    object = VkObjectSerializer()

    group_id = serializers.IntegerField()
    secret = serializers.CharField(max_length=200)

# view.py
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from .serializers import VkBaseSerializer


class VkCallbackView(CreateAPIView):
    serializer_class = VkBaseSerializer

    def create(self, request, *args, **kwargs):
        """
        Method is validate json in view
        """
        valid_ser = self.serializer_class(data=request.data)
        if valid_ser.is_valid():
            return Response('True')
        return Response('False')

有效数据:

>>> valid_ser.data
{
    "type": "str",
    "object": {
        "lead_id": 123,
        "group_id": 12345,
        "user_id": 12352,
        "form_id": 1
    },
    "group_id": 5123,
    "secret": "str"
}

答案非常有帮助: