返回顶部

利用json-Schema 对 Json 数据进行校验

安装

 pip install jsonschema

校验的参数为字符串和数字

from jsonschema  import  validate

schema  =  {
    "type":"object",
    "properties":{
        "price" : {"type" :"number"},
        "name":{ "type" :"string" }
    }
}

validate(instance = { "name" :"Eggs" , "price" :34.99 },schema = schema ) # pass

validate(instance = { "name" :"Eggs" , "price" :'d'},schema = schema )

  

 

校验的参数为列表,并且里面的元素为string类型

from jsonschema  import  validate

schema  =  {
    "type":"object",
    "properties":{
        'tag': {
            'type': 'array',
            'items': {
                "type": "string"
            }

        }
    }
}

validate(instance = { "tag" :['age','name']},schema = schema ) # pass

validate(instance = {  "tag" :[1,2,3]},schema = schema )

 

校验的参数为枚举类型

from jsonschema  import  validate

schema  =  {
    "type":"object",
    "properties":{
        "action": {"enum": ["resume", "down"]}
    }
}

validate(instance = { "action" :'resume'},schema = schema ) # pass

validate(instance = {  "action" :'d'},schema = schema )

  

 

校验的参数中必填的参数

from jsonschema import validate

schema = {
    "type": "object",
    "properties": {
        "action": {"enum": ["resume", "down"]},
        "name": {"type": "string", 'minLength': 1, 'maxLength': 100},
    },
    'required': ['name']
}

validate(instance={"action": 'resume','name': 'zhangbiao'}, schema=schema)  # pass
validate(instance={"action": 'resume'}, schema=schema)  # faild

 

 

嵌套json的校验

from jsonschema import validate

schema = {"type": "object",
          "properties": {
              "resumejobid": {"type": "integer", "minimum": 0},
              "parameters": {
                  "type": "object",
                  "properties": {
                      "name": {"type": "string"},
                      "queue": {"type": "string"},
                      "workspace": {"type": "string"},
                  },
                  "required": ["name", "queue","workspace"]
              },
          },
          "required": ["parameters", "resumejobid"]
          }

validate(instance={"parameters": {"name": "", "queue": "", "workspace": ""},
                   'resumejobid': 12}, schema=schema)  # pass

在django中 使用jsonschema 做参数校验 

 

from jsonschema import validate
from six import raise_from
from jsonschema import ValidationError, validate
from rest_framework.views import APIView
from django.shortcuts import render, HttpResponse

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_400_BAD_REQUEST


class CustomBaseException(APIException):
    status_code = HTTP_400_BAD_REQUEST
    message = 'Antilles api error'
    error_code = 1000

    def __init__(self, msg=None):
        super(CustomBaseException, self).__init__(msg)
        self.detail = {
            'msg': (msg or self.message),
            'errid': str(self.error_code)
        }

    def __str__(self):
        return '{}: error_code {}, "{}"'.format(
            self.__class__.__name__,
            self.detail.get('error_code', None),
            self.detail.get('msg', None),
        )

class InvalidJson(CustomBaseException):
    error_code = 1002
    message = 'Invalid JSON'

    def __init__(self, msg=None):
        self.detail = {
            'msg': self.message,
            'errid': str(self.error_code)
        }


def json_validate(schema):
    def valieated_func(func):
        def _func(self, request, *args, **kwargs):
            try:
                validate(request.data, schema)
            except ValidationError as e:
                raise_from(InvalidJson, e)
            else:
                return func(self, request, *args, **kwargs)
        return _func
    return valieated_func

class DetailView(APIView):
    @json_validate(
        {"type": "object",
         "properties": {
             "age": {"type": "integer", "minimum": 0},
             "parameters": {
                 "type": "object",
                 "properties": {
                     "name": {"type": "string", "minLength": 1, "maxLength": 100},
                     "queue": {"type": "string", "minLength": 1, "maxLength": 100},
                     "workspace": {"type": "string", "minLength": 1, "maxLength": 100},
                 },
                 "required": ["name", "queue", "workspace"]
             },
         },
         "required": ["parameters", "age"]
         }
    )
    def post(self, request):
        return HttpResponse("上传OK")

 

POST传输的参数为

{
    "parameters":{"name": "", "queue": "", "workspace": ""},
    "age": 12
}

  

 

 

Json schema 高级用法

https://www.cnblogs.com/terencezhou/p/10474617.html
https://json-schema.org/understanding-json-schema/index.html

  

  

 

posted @ 2019-03-04 18:24  Crazymagic  阅读(4350)  评论(0编辑  收藏  举报