skip to Main Content

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


  1. Your code works for me, it’s usually good practise to use get to prevent KeyErrors like that, so instead of s = session['example'] do s = session.get('example', 'default value')

    
    from flask import Flask, session
    
    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 session['example']
    
    @app.route('/export')
    def second():
        s = session.get('example', 'YourDefaultValueHere')
        print(s)
        return session['example']
    
    if __name__ == '__main__':
        app.run()
    
    Login or Signup to reply.
  2. The code you posted is working as expected.

    Here are some things you can check:

    1. Make sure the key you used to save in session in first is the exact same key you used to get from session in second. I know your sample code already shows the same key example, but your actual code may not be using the same key or it was somehow removed from session.

      You can check the contents of session by printing session.items() (like a dict):

      print(session.items())
      print(session['example'])
      
      # 127.0.0.1 - - [12/Oct/2019 16:03:52] "GET /export HTTP/1.1" 200 -
      # dict_items([('example', 'example1')])
      # example1
      
    2. Make sure you are accessing the correct route (first) that updates session. For example, while I was testing your sample code, I was accidentally refreshing /export instead of accessing the correct route at /.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search