Passing Variables Between Flask Pages
In Flask, you may encounter the need to pass variables between different pages. Suppose you have two pages, /a and /b, where you want to pass a NumPy array a from page /a to page /b.
Solution Using Session
If you wish to pass data without exposing it to the user, you can utilize Flask's session object:
@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 dictionary and can store JSON-serializable data. However, it's advisable to avoid storing large amounts of data in the session due to browser size limitations.
Solution Using URL Parameters
If you want to pass data along with a URL, you can employ query parameters:
<a href="{{ url_for('b', my_var='my_value') }}">Send my_value</a>
This will generate the URL:
/b?my_var=my_value
Within page /b, you can retrieve the data using:
@app.route('/b') def b(): my_var = request.args.get('my_var', None)
The above is the detailed content of How Can I Pass Variables Between Different Flask Pages?. For more information, please follow other related articles on the PHP Chinese website!