How to pass a variable between Flask pages?

Suppose I have the following case:

@app.route('/a', methods=['GET']) def a(): a = numpy.ones([10,10]) ... return render_template(...) # this rendered page has a link to /b @app.route('/b', methods=['GET']) def b(): print a .... 

There is one link on the lagging page that directs the / a page to / b. I am trying to pass the variable a to the / b page to reuse it. How do I make this Flask app? Do I need to use a session or is there another solution?

+17
python flask
source share
2 answers

If you want to pass some python value that the user should not see or control, you can use a 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 

A session behaves like a dict and is serialized in JSON. This way you can put everything that JSON serializes into the session. However, note that most browsers do not support session cookies larger than ~ 4000 bytes.

Avoid placing large amounts of data in a session, as they must be sent to and from the client with each request. For large amounts of data, use a database or other data warehouse. See Are global variables safe in a thread How can I share data between requests? and store big data or a service connection in a Flask session .


If you want to pass the value from the template to the URL, you can use the query parameter:

 <a href="{{ url_for('b', my_var='my_value') }}">Send my_value</a> 

will give out 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) 
+47
source share

The link to the /b route in the template for /a may contain query parameters that you could read on the route for /b . Alternatively, you can store the value for a in a session variable to access it between views.

+1
source share

All Articles