pythonjsonapiflaskjsonify

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. 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]>

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']

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

This is function that returns jsonify

# # 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.

What I want is when I store post_new_cafe() into response variable to have this

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

{"success": "Successfully added the new cafe."}

print(data["success"])

Successfully added the new cafe.


Solution

  • Hey you can solve this issue with the json library.

    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

    If you need to serialize a numpy array, there is a question on how to serialize a numpy array as 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'))