烧瓶中休息端点的装饰器。验证json请求数据。
flask-expects-json的Python项目详细描述
flask需要json
烧瓶中休息端点的装饰器。验证json请求数据。
在构建json rest服务时,我发现自己已经指定了 定义swagger规范时post数据的json模式。 将json验证带到flask。它忽略了验证数据的需要 在从已经确立的标准中获利的同时 (http://json-schema.org/)。在路由之前定义架构 帮助端点的自文档(请参阅用法)。
此包使用jsonschema to进行验证: https://pypi.python.org/pypi/jsonschema
使用量
这个包提供了一个flask路由装饰器来验证json负载。
fromflaskimportFlask,jsonify,g,url_forfromflask_expects_jsonimportexpects_json# example importsfrommodelsimportUserfromormimportNotUniqueErrorapp=Flask(__name__)schema={'type':'object','properties':{'name':{'type':'string'},'email':{'type':'string'},'password':{'type':'string'}},'required':['email','password']}@app.route('/register',methods=['POST'])@expects_json(schema)defregister():# if payload is invalid, request will be aborted with error code 400# if payload is valid it is stored in g.data# do something with your datauser=User().from_dict(g.data)try:user.save()exceptNotUniqueErrorase:# exception path: duplicate database entryreturnjsonify(dict(message=e.message)),409# happy path: json responseresp=jsonify(dict(auth_token=user.encode_auth_token(),user=user.to_dict()})resp.headers['Location']=url_for('users.get_user',user_id=user.id)returnresp,201
预期的json负载可以通过“schema”识别。如果架构是 不满足请求中止(400)并显示提示错误消息。
mimetype检查
从1.2.0开始,此装饰程序使用flask.request.get_json(force=False) 去获取数据。这意味着请求的mimetype必须是 “应用程序/json”。可通过设置force=False禁用。注意 这造成了CSRF的一个主要安全漏洞,因为CORS 对某些mimetype不强制。感谢Argishti Rostamian 注意到了。
@app.route('/strict')@expects_json()defstrict():return'This view will return 400 if mimetype is not \'application/json\'@app.route('/insecure')@expects_json({},force=False)definsecure():return'This view will validate the data no matter the mimetype.'
默认值
通常验证器不会接触数据。默认情况下,此包将 不填写架构中缺少的默认值。如果你愿意 可以显式设置fill_default=True。验证将是 在此操作之后执行,因此默认值可能导致无效数据。
测试
pythonsetup.pytest
更改日志
1.3.0-2018-02-16
已更改
- 默认情况下,不会在请求数据中填写默认值。套
fill_defaults=显式为true。
1.2.0-2018-02-15
已更改
- 安全性:将force=false设置为默认参数。前:力=真
1.0.6-2018-01-29
- 代码样式/自述文件更改。
- 为python 3.4、3.5、3.6添加测试
- 为正确的CI和自动释放所做的更改
- 添加代码覆盖率
1.0.0-2018-01-21
已添加
- expects_json()decorator的初始版本
- 请求数据的简单验证
- 将数据存储在g.data中