使用框架对json体做参数验证

来源:互联网 发布:淘宝手机单 编辑:程序博客网 时间:2024/06/06 03:33

使用框架对json体做参数验证

在API接口开发过程中,大多文档对接口的属性有严格要求,这需要接收端对Json信息体做参数校验,屏蔽不合理的入参。

记录下目前接触到的对json体进行校验的框架,刚好工作中有用到

1.采用wsme中的类型定义,对json体参数进行限制

通过from wsme import types as wtypes 导入使用,就使用wsme.types中的类限定json体的参数属性,具体示例如下:

class LoadBalancerPOST(base.BaseType):"""Defines mandatory and optional attributes of a POST request."""id = wtypes.wsattr(wtypes.UuidType())name = wtypes.wsattr(wtypes.StringType(max_length=255))    ###限定最大长度description = wtypes.wsattr(wtypes.StringType(max_length=255))enabled = wtypes.wsattr(bool, default=True)   ###设置参数默认值vip = wtypes.wsattr(VIP, mandatory=True)      ####VIP为vip的数据类型定义,mandatory标识参数vip为必填项project_id = wtypes.wsattr(wtypes.StringType(max_length=36))listeners = wtypes.wsattr([listener.ListenerPOST], default=[])

具体查看wsattr类定义,定义复合类型的属性

datatype:参数类型

mandatory:控制参数为可选项和必选项

default: 设置参数的默认值

readonly :控制该参数只读性

class wsattr(object):    """    Complex type attribute definition.    Example::        class MyComplexType(wsme.types.Base):            optionalvalue = int            mandatoryvalue = wsattr(int, mandatory=True)            named_value = wsattr(int, name='named.value')    After inspection, the non-wsattr attributes will be replaced, and    the above class will be equivalent to::        class MyComplexType(wsme.types.Base):            optionalvalue = wsattr(int)            mandatoryvalue = wsattr(int, mandatory=True)    """    def __init__(self, datatype, mandatory=False, name=None, default=Unset,                 readonly=False):        #: The attribute name in the parent python class.        #: Set by :func:`inspect_class`        self.key = None  # will be set by class inspection        #: The attribute name on the public of the api.        #: Defaults to :attr:`key`        self.name = name        self._datatype = (datatype,)        #: True if the attribute is mandatory        self.mandatory = mandatory        #: Default value. The attribute will return this instead        #: of :data:`Unset` if no value has been set.        self.default = default        #: If True value cannot be set from json/xml input data        self.readonly = readonly        self.complextype = None

查看StringType类定义,里面就可以进一步限定参数类型,如字符串的长度,式样等。

class StringType(UserType):    """    A simple string type. Can validate a length and a pattern.    :param min_length: Possible minimum length    :param max_length: Possible maximum length    :param pattern: Possible string pattern    Example::        Name = StringType(min_length=1, pattern='^[a-zA-Z ]*$')    """    basetype = six.string_types    name = "string"    def __init__(self, min_length=None, max_length=None, pattern=None):        self.min_length = min_length        self.max_length = max_length        if isinstance(pattern, six.string_types):            self.pattern = re.compile(pattern)        else:            self.pattern = pattern    def validate(self, value):        if not isinstance(value, self.basetype):            error = 'Value should be string'            raise ValueError(error)        if self.min_length is not None and len(value) < self.min_length:            error = 'Value should have a minimum character requirement of %s' \                    % self.min_length            raise ValueError(error)        if self.max_length is not None and len(value) > self.max_length:            error = 'Value should have a maximum character requirement of %s' \                    % self.max_length            raise ValueError(error)        if self.pattern is not None and not self.pattern.search(value):            error = 'Value should match the pattern %s' % self.pattern.pattern            raise ValueError(error)        return value

2.使用Python的jsonschema对json 做验证

>>> from jsonschema import validate>>> # A sample schema, like what we'd get from json.load()>>> schema = {...     "type" : "object",...     "properties" : {...         "price" : {"type" : "number"},...         "name" : {"type" : "string"},...     },... }>>> # If no exception is raised by validate(), the instance is valid.>>> validate({"name" : "Eggs", "price" : 34.99}, schema)>>> validate(...     {"name" : "Eggs", "price" : "Invalid"}, schema... )                                   # doctest: +IGNORE_EXCEPTION_DETAILTraceback (most recent call last):    ...ValidationError: 'Invalid' is not of type 'number'

目前自己使用框架1

具体参考

jsonschema 2.6.0

JSON Schema Introduction

JSON Schema Validation: A Vocabulary for Structural Validation of JSON

使用 Python 的 jsonschema 对 json 做验证

原始链接,欢迎学习指正

阅读全文
0 0
原创粉丝点击