我试图使用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

其他回答

{
  "uuid":1212121212,
  "text":"lalala",
  "comment":"",
  "signed_on":"2022-11-07 00:03:00"
}

您可以将上述数据作为json发送,并使用request.json在flask应用程序中获取它

from flask import request, Blueprint,flash,json

@app.route('/api/add_message/<uuid>', methods = ["GET", "POST"])
def testing(uuid):
    sync_data = request.json    
    josn_data = json.dumps(sync_data ,default =str)
    return josn_data

对于所有那些问题来自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()

作为参考,以下是如何从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)

给出另一种方法。

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/service', methods=['POST'])
def service():
    data = json.loads(request.data)
    text = data.get("text",None)
    if text is None:
        return jsonify({"message":"text not found"})
    else:
        return jsonify(data)

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

假设您已经发布了带有application/ JSON内容类型的有效JSON,请求。json将有解析的json数据。

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/echo', methods=['POST'])
def hello():
   return jsonify(request.json)