Flask Web框架的基本JSON模式验证器。
Flask-JsonSchemaValidator的Python项目详细描述
烧瓶jsonschemavalidator
Flaskweb框架的基本json模式验证器。
用法
基本用法是将@validate
decorator应用于路由。如果请求验证,则将按正常方式调用路由。如果请求未验证,将生成一条错误消息,并返回一条400 BAD REQUEST
,同时返回正文中的错误消息。
validate(schema, force=False, json_cache=True)
架构:jsonschema根据
强制:如果Content-Type
不是applciation/json
,则尝试验证请求
json缓存:使用flask.request.get_json
示例
fromflask_jsonschemaimportvalidate@app.route("/",methods=['POST'])@validate({'type':'object','properties':{'foo':{'type':'string'},'bar':{'type':'number'},},'required':['bar','foo'],})defindex_post():returnflask.jsonify(time=time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
有效请求
请求:
POST/HTTP/1.1Content-Type:application/jsonHost:localhost:5000Content-Length:26{"foo":"String","bar":123}
响应:
HTTP/1.0200OKContent-Type:application/jsonContent-Length:35Server:Werkzeug/0.10.4 Python/3.4.3Date:Thu, 27 Aug 2015 04:05:24 GMT{"time":"2015-08-27 04:05:24"}
无效请求
请求:
POST/HTTP/1.1Content-Type:application/jsonHost:localhost:5000Content-Length:37{"foo":"String","bar":"Not a number"}
响应:
HTTP/1.0400BAD REQUESTContent-Type:application/jsonContent-Length:145Server:Werkzeug/0.10.4 Python/3.4.3Date:Thu, 27 Aug 2015 03:53:39 GMT{"error_message":"'Not a number' is not of type 'number'","error_path":"(root).bar","status":400,"status_message":"Bad Request"}