使用模式文件和路由装饰器验证flask json请求数据
flask-jsonschema-validator的Python项目详细描述
flask json模式验证器
使用模式文件和路由装饰器验证flask json请求数据。
作者
丹尼尔'矢量'克尔(vector@vector.id.au)
许可证
请参阅LICENSE.txt。
安装
pip安装烧瓶jsonschema验证器
示例用法
python代码
main.py
fromflaskimportFlask,request,jsonifyfromflask_jsonschema_validatorimportJSONSchemaValidatorapp=Flask()JSONSchemaValidator(app=app,root="schemas")# Define a normal flask route, and then apply the `validate` decorator.# Look for the `users.json` file, and use the `register` key as the schema source.@app.route('/register',methods=['POST'])@app.validate('users','register')defrouteRegister():user=request.jsonreturnjsonify(user)if__name__=='__main__':app.run(port=8080)
架构文件
schemas/users.json
{"register":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":100},"email":{"type":"string","format":"email"},"password":{"type":"string","minLength":8,"maxLength":32}},"required":["name","email","password"]}}
运行服务器
python main.py
将数据发布到服务器
POST/registerHTTP/1.0Content-Type:application/jsonContent-Length:76{"name":"fred","email":"fred@foo.com","password":"frediscool"}
处理验证错误
如果数据验证正确,那么服务器将以json对象的形式响应post数据。
如果数据无法验证,将引发jsonschema.ValidationError
异常。
要处理异常,可以注册一个flask errorhandler。例如:
importjsonschemafromflaskimportResponse@app.errorhandler(jsonschema.ValidationError)defonValidationError(e):returnResponse("There was a validation error: "+str(e),400)