pass variable from python 28flask 29 to html in redirect

Solutions on MaxInterview for pass variable from python 28flask 29 to html in redirect by the best coders in the world

showing results for - "pass variable from python 28flask 29 to html in redirect"
Bertille
02 Sep 2018
1Question:
2In flask, I can do this:
3
4render_template("foo.html", messages={'main':'hello'})
5And if foo.html contains {{ messages['main'] }}, the page will show hello. But what if there's a route that leads to foo:
6
7@app.route("/foo")
8def do_foo():
9    # do some logic here
10    return render_template("foo.html")
11In this case, the only way to get to foo.html, if I want that logic to happen anyway, is through a redirect:
12
13@app.route("/baz")
14def do_baz():
15    if some_condition:
16        return render_template("baz.html")
17    else:
18        return redirect("/foo", messages={"main":"Condition failed on page baz"}) 
19        # above produces TypeError: redirect() got an unexpected keyword argument 'messages'
20So, how can I get that messages variable to be passed to the foo route, so that I don't have to just rewrite the same logic code that that route computes before loading it up?
21
22Answer:
23You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:
24
25from flask import session, url_for
26
27def do_baz():
28    messages = json.dumps({"main":"Condition failed on page baz"})
29    session['messages'] = messages
30    return redirect(url_for('.do_foo', messages=messages))
31
32@app.route('/foo')
33def do_foo():
34    messages = request.args['messages']  # counterpart for url_for()
35    messages = session['messages']       # counterpart for session
36    return render_template("foo.html", messages=json.loads(messages))
37(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
38
39Or you could probably just use Flask Message Flashing if you just need to show simple messages.