validator.py 1.3 KB
Newer Older
F
feilong 已提交
1
# -*- coding: UTF-8 -*-
F
feilong 已提交
2
# 作者:huanhuilong
F
feilong 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
# 标题:参数校验
# 描述:使用 jsonschema 校验参数,key:字符串类型, value:数字, condition: 数字

from error_code import ErrorCode
from jsonschema import validate
import json
import logging
import traceback
logger = logging.getLogger(__name__)


class KeyValueValidator:
    def __init__(self) -> None:
        pass

    def validate(self, req, required):
        schema = {
            "type": "object",
            "properties": {
                "key": {"type": "string"},
                "value": {"type": "number"},
                "condition": {"type": "number"},
            },
            "required": required
        }

        try:
            validate(instance=req, schema=schema)
            return {
                'err': ErrorCode.SUCCESS
            }
        except Exception as e:
            logger.error(f"validate exception:{str(e)}")
            logger.error(traceback.format_exc())
            return {
                'err': ErrorCode.INVALID_PARAMETERS
            }


if __name__ == '__main__':
    v = KeyValueValidator()

    ret = v.validate({'key': "test", 'value': 100}, ['key', 'value'])
    assert ret['err'] == ErrorCode.SUCCESS

    ret = v.validate({'key': "test"}, ['key', 'value'])
    assert ret['err'] == ErrorCode.INVALID_PARAMETERS