我试图使用Flask构建一个简单的API,在其中我现在想读取一些post JSON。我用邮递员Chrome扩展做POST, JSON I POST只是{"text":"lalala"}。我尝试使用以下方法读取JSON:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
在浏览器上,它正确地返回我放入GET中的UUID,但在控制台上,它只是打印出None(我希望它打印出{"text":"lalala"})。有人知道我如何从Flask方法中获得发布的JSON吗?
尽管我在这里遇到的所有答案都是正确的。有一件事我认为应该做,作为更好的实践。我是这样写的。
from flask import app, request, Flask, jsonify
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
# Check if the request method is POST
if request.method == 'POST':
# content will return eather parse data as JSON
# Or None incase there is no data
content = request.get_json()
print(content)
# The content could be displayed in html page if serialized as json
return jsonify(content) # Return null if there is content
# if it is only get request then just return uuid
return uuid
作为参考,以下是如何从Python客户端发送json的完整代码:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print(res.json())
“json=”输入将自动设置内容类型,如这里所讨论的:如何POST json数据与Python请求?
上面的客户端将与服务器端代码一起工作:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print(content['mytext'])
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
对于所有那些问题来自ajax调用的人,这里有一个完整的例子:
Ajax调用:这里的关键是使用dict,然后使用JSON.stringify
var dict = {username : "username" , password:"password"};
$.ajax({
type: "POST",
url: "http://127.0.0.1:5000/", //localhost Flask
data : JSON.stringify(dict),
contentType: "application/json",
});
在服务器端:
from flask import Flask
from flask import request
import json
app = Flask(__name__)
@app.route("/", methods = ['POST'])
def hello():
print(request.get_json())
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
if __name__ == "__main__":
app.run()