flask request json

0x00

flask 获取 request json 数据

0x01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding:utf-8 _*-  
"""
@author: ronething
@time: 2019-02-27 22:25
@mail: axingfly@gmail.com

Less is more.
"""

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route("/test", methods=["POST"])
def hello():
"""
如果使用 request.json
当 Headers 设置 Content-Type application/json 而 body 有传空 不是 {} 的时候会报以下错误
<p>Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>
如果使用 request.get_json(silent=True) 接的 silent=True 静默模式开启就不会报错
返回的是 None
于是建议用第二种
:return:
"""
# request_json = request.json
request_json = request.get_json(silent=True)
print(request_json)
return jsonify(request_json)


if __name__ == '__main__':
app.run(debug=True)
Author: ronething
Link: https://blog.ronething.cn/20190321-flask.html
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.