Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError when using session in Flask

Tags:

python

flask

So I am trying to pass a value from one html page to another using flask. The code I have written looks like this:

from flask import Flask, render_template
from flask import request, session, url_for,abort,redirect

app = Flask(__name__)

app.config['SECRET_KEY'] = 'oh_so_secret'


@app.route('/'):
def first():
    session['this_one']='hello'
    render('template.html')

@app.route('/second')
def second():
   it=session['this_one']
    render('other_page.html')

if __name__ == '__main__':
    app.run(debug=True)

but when I run this I get a KeyError:this_one.

So, it works today, having restarted the system. I then made some changes:

@app.route('/'):
def first():
    session['this_one']='goodbye'
    render('template.html')

@app.route('/second')
def second():
   it=session['this_one']
   render('other_page.html')

and the second function is still returning hello.

So it seems that the session dictionary is not being overwritten as I would want it to be.

Follow Up

This is a real mystery, it works one day then not the next with no changes being made. Now in the rout ('/') I am setting a list:

@app.route('/'):
def first():
    session['this_one']='hello'
    session['a_list']=['a','b','c']
    render('template.html')

calling it in the second function with a print command:

@app.route('/second')
def second():
    it=session['this_one']
    print(session['a_list'])
    render('other_page.html')

and an empty list [] is returned.

like image 656
laila Avatar asked Sep 04 '26 17:09

laila


1 Answers

Your code works fine (aside from indentation problems, which I assume are typos here and not in the actual code). What must be happening is the second page is being visited before the first. You could use exception handling to check for a KeyError and redirect to the first page if it is encountered.

like image 142
Bob Dylan Avatar answered Sep 07 '26 06:09

Bob Dylan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!