I have a problem because I want to include values in the session. When I save the values in one app.route
and later I need to go to another link and use this value, I get a KeyError
. What am I doing wrong?
from flask import Flask, render_template, request, session
from OPTYMALIZACJA import OPTYMALIZACJA
app = Flask(__name__)
app.secret_key = "abc"
app.config['SESSION_TYPE'] = 'memcached'
@app.route('/', methods=['POST', 'GET'])
def first():
# calculation instructions
session['example'] = 'example1'
return render_template('index.html')
@app.route('/export')
def second():
s = session['example']
print(s)
return render_template('index.html')
In index.html
I have a link to the localhost/export
page.
2
Answers
Your code works for me, it’s usually good practise to use
get
to prevent KeyErrors like that, so instead ofs = session['example']
dos = session.get('example', 'default value')
The code you posted is working as expected.
Here are some things you can check:
Make sure the key you used to save in
session
infirst
is the exact same key you used to get fromsession
insecond
. I know your sample code already shows the same keyexample
, but your actual code may not be using the same key or it was somehow removed fromsession
.You can check the contents of
session
by printingsession.items()
(like adict
):Make sure you are accessing the correct route (
first
) that updatessession
. For example, while I was testing your sample code, I was accidentally refreshing /export instead of accessing the correct route at /.