search by tags

for the user

adventures into the land of the command line

passing data between views in flask using sessions

in this example, we are going to pass a variable called my_groovy_data from one view to another.

first you gotta import session from flask

from flask import session

then at the top, session needs a secret_key

app = Flask(__name__)
app.secret_key = 'super_secret_key'

view one is called ‘hello’, and on a POST, session data is set and then the client is redirected to another view called 'index’

@app.route('/hello', methods=['POST', 'OPTIONS'])
def hello():
    page_name = 'hello'
    if request.method == 'POST':
        session['my_groovy_data'] = "my_groovy_data"
        return redirect(url_for('index'))

this is the view that is redirected to, 'index’ and on a GET, if the session data contains a key called 'my_groovy_data’, grab it and render the index.html template, with the value sent also to the template.

@app.route('/', methods=['GET'])
def index():
    page_name = '/'
    if session.get('my_groovy_data', None):
        my_groovy_data = session.get('my_groovy_data', None)
        return render_template('index.html', my_groovy_data=my_groovy_data)
        return render_template('index.html')

then do it

if __name__ == '__main__':