1. 程式人生 > 其它 >使用jsonschema進行引數校驗

使用jsonschema進行引數校驗

1.安裝jsonschema

**pip install jsonschema**

2.程式碼

點選檢視程式碼
from jsonschema import validate


def verify_code_2_member(data: dict):
    schema = {
        "type": "object",
        "additionalProperties": True,
        "required": ["code", "account_id", "telephone"],
        "properties": {
            "code": {
                "type": "string",
                "description": "兌換碼",
                "minLength": 9,
                "maxLength": 9,
            },
            "account_id": {
                "type": "integer",
                "description": "賬號"
            },
            "telephone": {
                "type": "string",
                "description": "手機號",
                "pattern": "^1[3-9]\d{9}$"
            }
        }
    }

    return __validator(data, schema)

def __validator(data, schema):
    try:
        validate(data, schema)
        return True, None

    except Exception as e:
        return False, str(e).split("\n")[0]

3.使用

_res, _err = verify_code_2_member(body)