How to pass a variable between Flask pages?

If you want to pass some python value around that the user doesn’t need to see or have control over, you can use the session:

@app.route('/a')
def a():
    session['my_var'] = 'my_value'
    return redirect(url_for('b'))

@app.route('/b')
def b():
    my_var = session.get('my_var', None)
    return my_var

The session behaves like a dict and serializes to JSON. So you can put anything that’s JSON serializable in the session. However, note that most browsers don’t support a session cookie larger than ~4000 bytes.

You should avoid putting large amounts of data in the session, since it has to be sent to and from the client every request. For large amounts of data, use a database or other data storage. See Are global variables thread safe in flask? How do I share data between requests? and Store large data or a service connection per Flask session.


If you want to pass a value from a template in a url, you can use a query parameter:

<a href="https://stackoverflow.com/questions/27611216/{{ url_for("b', my_var="my_value") }}">Send my_value</a>

will produce the url:

/b?my_var=my_value

which can be read from b:

@app.route('/b')
def b():
    my_var = request.args.get('my_var', None)

Leave a Comment