python web开发中对大量参数的校验(返回自定义错误提示)

@(学无止境)

python web开发中对大量参数的校验(返回自定义错误提示)

安装schema

pip install schema

校验创建账号的参数

  • name: string 由7—15个字母、数字、下划线组成
  • phone: string 11位手机号
  • education: int 1:primary school; 2: junior high school; 3: High school; 4: bachelor; 5: master; 6: doctor
  • age: int [7-150] 可选
  • level: high、middle、low
  • grade: int 可选

校验示例(可直接运行)

我的运行环境:
python: 3.7.1
schema: 0.6.8

#!/usr/bin/env python
# -*- coding: utf-8 -*-


from schema import Regex, And, Use, Optional, Schema


def check_register_params(data):
    """ 校验创建新账号的参数
        name: string 由7—15个字母、数字、下划线组成
        phone: string 11位手机号
        education: int 1:primary school; 2: junior high school; 3: High school;
                        4: bachelor; 5: master; 6: doctor
        age: int [7-150] 可选
        level: high、middle、low
        grade: int 可选
    """
    level_list = ["high", "middle", "low"]
    mode_dict = {
        "name": Regex("[a-zA-Z0-9_]{7,15}", error="name应为7-15位字母、数字、下划线组成"),
        "phone": Regex("^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[678])[0-9]{8}$", error="手机号不正确"),
        "education": And(int, lambda x: 0 < x < 7, error="education应该为0-6之间的整数"),
        Optional("age", default="sing"): And(int, lambda x: 7 < x < 150, error="age应该为7-150之间的整数"),
        "level": And(str, lambda x: x in level_list, error="level的可选值为high、middle、low"),
        Optional("grade", default="90"): Use(int, error="应该为整数"),
    }
    try:
        results = Schema(mode_dict).validate(data)
    except Exception as ex:
        print("Error: %s" % ex)
    else:
        print("结果是")
        print(results)

if __name__ == '__main__':
    # 验证通过的参数
    # data = {
    #     "name": "12345678",
    #     "phone": "18329269224",
    #     "education": 6,
    #     "age": 8,
    #     "level": "middle",
    #     "grade":86
    # }
    # check_register_params(data)

    # name不合法
    # data = {
    #     "name": "123",
    #     "phone": "18329269224",
    #     "education": 6,
    #     "age": 8,
    #     "level": "middle",
    #     "grade":86
    # }
    # check_register_params(data)

    # 少了必填参数
    data = {
        "name": "hji123345",
        "phone": "18329269224"
    }
    check_register_params(data)

依次放开main中注释的内容,得到的输出结果:

验证通过的参数

image.png

name不合法

image.png

少了必填参数

image.png

参考资料:

https://blog.csdn.net/y472360651/article/details/81949653
https://shengxin.ren/article/211

你可能感兴趣的:(python web开发中对大量参数的校验(返回自定义错误提示))