The server comes with json format:
{
"type": "string",
"object": {
"lead_id": int,
"form_name": "string",
"answers": [
{
"lead_id": int,
"key": "string",
}
...
]
},
"group_id": int,
"secret": "string"
}
How to use django REST framework to validate this json?
ru version
You can use django rest framework to write you own validators like so,
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)
You can find more details here
Hope this helps!
Example:
# 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 data:
>>> valid_ser.data
{
"type": "str",
"object": {
"lead_id": 123,
"group_id": 12345,
"user_id": 12352,
"form_id": 1
},
"group_id": 5123,
"secret": "str"
}
The answers were very helpful:
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={})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With