laila
laila

Reputation: 1059

KeyError when using session in 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.

Upvotes: 5

Views: 31609

Answers (5)

ovntatar
ovntatar

Reputation: 416

the key parameter has been changed to '_user_id'

Upvotes: 0

avijit
avijit

Reputation: 911

I have faced the same error. My flask application using flask-login 0.4.1 worked fine for me in my test server. However, when I migrated to a development server, I get keyerror 'user_id' not found in session. I was surprised why this error is given as same code is working fine in my test server. Later, after my investigation I found that my production server is using flask-login 0.5.0 which updated some default values which caused the error. So, I down-graded flask-login version to 0.4.1 and restarted the apache server which worked fine my application then.

Upvotes: 1

laila
laila

Reputation: 1059

After 2 weeks of banging my head against the desk I found the error, I was rendering the wrong page .. my original code actually looked like:

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 pre-first():
    return render_template('template_old.html')

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

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

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

by changing the first function to:

@app.route('/'):
def pre-first():
    return render_template('template.html')

it worked.

Upvotes: 3

Bob Dylan
Bob Dylan

Reputation: 1833

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.

Upvotes: 6

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

Assuming all the formatting errors inside your code are just typos, your code works exactly as you expect.

from flask import Flask, session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'oh_so_secret'


@app.route('/')
def first():
    session['this_one'] = 'hello'
    return 'Hello was saved into session[this_one].'


@app.route('/second')
def second():
    return 'Value inside session[this_one] is {}.'.format(session['this_one'])


if __name__ == '__main__':
    app.run(debug=True)
  1. Open http://127.0.0.1:5000/, you will get: Hello was saved into session[this_one].
  2. Open http://127.0.0.1:5000/second, you will get: Value inside session[this_one] is hello. Which is taken from session.

Upvotes: 2

Related Questions