Home > Backend Development > Python Tutorial > How Can I Pass Variables Between Different Flask Pages?

How Can I Pass Variables Between Different Flask Pages?

Barbara Streisand
Release: 2024-12-09 04:43:22
Original
291 people have browsed it

How Can I Pass Variables Between Different Flask Pages?

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
Copy after login

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>
Copy after login

This will generate the URL:

/b?my_var=my_value
Copy after login

Within page /b, you can retrieve the data using:

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template