flask接口参数校验 jsonschema 的使用
开头
flask接口开发中参数校验可以用到的方法有很多,但是我比较喜欢跟前端的js检验类似,故选用到了 jsonschema 这个参数校验的库
Demo
下面是一个比较全的参数校验的接口,日后方便参考 官方链接
from jsonschema import validate, ValidationError # 导入参数的包
@app.route(‘/login4‘, methods=[‘POST‘])
def login4():
body = request.get_json()
try:
validate(
body,
{
"$schema": "http://json-schema.org/learn/getting-started-step-by-step",
# 描述对应的JSON元素,title相对来说,更加简洁
"title": "book info",
# 描述对应的JSON元素,description更加倾向于详细描述相关信息
"description": "some information about book",
# 该关键字用于限定待校验JSON元素所属的数据类型,取值可为:object,array,integer,number,string,boolean,null
"type": "object",
# 用于指定JSON对象中的各种不同key应该满足的校验逻辑,
# 如果待校验JSON对象中所有值都能够通过该关键字值中定义的对应key的校验逻辑,每个key对应的值,都是一个JSON Schema,则待校验JSON对象通过校验。
"properties": {
"id": {
"description": "The unique identifier for a book",
"type": "integer",
"minimum": 1
},
"name": {
"description": "book name",
"type": "string",
"minLength": 3,
"maxLength": 30
},
"info": {
"description": "simple information about book",
"type": "string",
"minLength": 10,
"maxLength": 60
},
"tips": {
"anyOf": [ # 满足其中一个类型 就行
{"type": "string", "minLength": 10, "maxLength": 60},
{"type": "number", "minimum": 5.0}
]
},
"price": {
"description": "book price",
"type": "number",
# 能被0.5整除
"multipleOf": 0.5,
# 这里取等,5.0= ".join([i for i in e.path]), e.message)
print(msg)
return jsonify(status=500, msg=msg)
print(body)
title = body.get(‘title‘)
return ‘1‘
完。
原文:https://www.cnblogs.com/c-keke/p/14888876.html