使用模式文件和路由装饰器验证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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
opencv Java RTSP从流数据包保存快照   java如何在websocket onopen事件中访问spring mvc属性值?   JAVAutil。scanner如何在scanner中使用分隔符。在Java中使用分隔符?   滚动滚动BuffereImage Java   记事本++的nppexec中的java\t间距   java Spring使用额外的字段让很多人冬眠   处理如何使用java中的JSON执行shell命令   java使用数据绑定库绑定需要其他组件的事件   java无法从YAML文件中删除特定的key:value   Java帮助:将字符串转换为ArrayList<Integer>   java在使用数组作为变量时没有得到完整的数组   调用Axis 2 Web服务时发生java端点引用错误   java禁用log4j 2异常(apache的异常)   在java11:javax上发送电子邮件给Log4j2 SMTP Appender。邮件或雅加达。邮政   java无论如何都有一个线程来捕获中断异常,而不仅仅是放置时间。单元秒。睡觉   java如何将Android导航架构片段动画化为在旧片段上滑动?   数字小数部分的操作问题   java如何反复提问,直到我作为一个角色得到正确的答案