简体   繁体   English

Flask jsonify 返回字节和字符串而不是 json object

[英]Flask jsonify returns bytes and string instead of json object

In Postman post_new_cafe prints json as it suppose to be, but when I want to print it inside console and webpage it prints differently.在 Postman post_new_cafe 打印 json ,但是当我想在控制台和网页中打印它时,它的打印方式不同。 See example below.请参见下面的示例。

@app.route('/add_form', methods=['GET', 'POST'])
def add_new_cafe_form():
    form = CafeForm()
    if form.validate_on_submit():
        response = post_new_cafe()
        print(response)
    return render_template("add.html", form=form)

This prints out这打印出来

<Response 52 bytes [200 OK]> <响应 52 字节 [200 OK]>

and

@app.route('/add_form', methods=['GET', 'POST'])
def add_new_cafe_form():
    form = CafeForm()
    if form.validate_on_submit():
        response = post_new_cafe()
        print(response.response)
    return render_template("add.html", form=form)

prints out打印出来

[b'{\n "success": "Successfully added the new cafe."\n}\n'] [b'{\n "success": "成功添加新咖啡馆。"\n}\n']

and this和这个

@app.route('/add_form', methods=['GET', 'POST'])
def add_new_cafe_form():
    form = CafeForm()
    if form.validate_on_submit():
        response = post_new_cafe()
        print(response.json())
    return render_template("add.html", form=form)

gives error给出错误

TypeError: 'dict' object is not callable类型错误:'dict' object 不可调用

This is function that returns jsonify这是返回 jsonify 的 function

# # HTTP POST - Create Record
@app.route('/add', methods=['POST'])
def post_new_cafe():
    new_cafe = Cafe(
        name=request.form.get('name'),
        map_url=request.form.get('map_url'),
        img_url=request.form.get('img_url'),
        location=request.form.get('location'),
        seats=request.form.get('seats'),
        has_toilet=bool(strtobool(request.form.get('has_toilet'))),
        has_wifi=bool(strtobool(request.form.get('has_wifi'))),
        has_sockets=bool(strtobool(request.form.get('has_sockets'))),
        can_take_calls=bool(strtobool(request.form.get('can_take_calls'))),
        coffee_price=request.form.get('coffee_price')
    )
    # db.session.add(new_cafe)
    # db.session.commit()
    return jsonify(success="Successfully added the new cafe.")

I have tried this我试过这个

resp = Response(response={"success":"Successfully added the new cafe."},
                status=200,
                mimetype="application/json")
return jsonify(resp)

and it's not working, also I have tried using make_response still nothing.它不起作用,我也尝试过使用 make_response 仍然没有。

What I want is when I store post_new_cafe() into response variable to have this我想要的是当我将 post_new_cafe() 存储到响应变量中时

response = post_new_cafe()
data = response.json()
print(data)

{"success": "Successfully added the new cafe."} {"success": "成功添加新咖啡馆。"}

print(data["success"])

Successfully added the new cafe.成功添加新咖啡厅。

Hey you can solve this issue with the json library.嘿,您可以使用 json 库解决此问题。

Example:例子:

import json

def post_new_cafe():
    new_cafe = Cafe(
        name=request.form.get('name'),
        map_url=request.form.get('map_url'),
        img_url=request.form.get('img_url'),
        location=request.form.get('location'),
        seats=request.form.get('seats'),
        has_toilet=bool(strtobool(request.form.get('has_toilet'))),
        has_wifi=bool(strtobool(request.form.get('has_wifi'))),
        has_sockets=bool(strtobool(request.form.get('has_sockets'))),
        can_take_calls=bool(strtobool(request.form.get('can_take_calls'))),
        coffee_price=request.form.get('coffee_price')
    )
    return json.dumps({"success": "Succesfully added the new cafe."})

response = post_new_cafe()
data = json.loads(response)
print(data)
print(data["success"])

For more information look at the Documentation about JSON有关更多信息,请查看有关 JSON 的文档

If you need to serialize a numpy array, there is a question on how to serialize a numpy array as JSON如果您需要序列化 numpy 数组,有一个关于如何将 numpy 数组序列化为 JSON的问题

Regarding your other issue:关于你的另一个问题:

@app.route('/add_form', methods=['GET', 'POST'])
def add_new_cafe_form():
    form = CafeForm()
    if form.validate_on_submit():
        response = post_new_cafe()
        print(response.json())
    return render_template("add.html", form=form)

You need to convert the response from binary to string first: response.decode('utf-8') and then parse it as JSON: json.loads(response.decode('utf-8'))您需要先将响应从二进制转换为字符串: response.decode('utf-8')然后将其解析为 JSON: json.loads(response.decode('utf-8'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM