Flask Responses in 3 common types

Flask is able to handle couple of accepted types of responses. I’ll summarize three most common ones:

  1. Text
  2. Json
  3. Template

Text

The simplest form

@index_page.route("/text")
def res_text():
    return "text or " + "<h2>html<h2>"

Alternatively, can use flask’s make_response method

@index_page.route("/text_response")
def res_text_res():
    res = make_response("text or " + "<h2>html<h2>", 200)
    return res

The result will be

Json

Json is a more commonly used format, particularly for developing FE and BE separately

@index_page.route("/json")
def res_json():
    import json
    data = {
        "a": 200
    }
    res = make_response(json.dumps(data))

    return res

Alternatively use flask’ jsonify method

@index_page.route("/json_jsonify")
def res_json_jsonify():
    data = {
        "a": 200
    }
    res = make_response(jsonify(data))
    return res

the result will be

Template

  • Use flask’s render_template method
  • Add templates folder, on the same level with application file
@index_page.route("/template")
def res_temp():
    return render_template("index.html")

result


   Reprint policy


《Flask Responses in 3 common types》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License
  TOC