Skip to content
Advertisement

Javascript store in session, get from session in python/flask

I am working with a flask app, and am trying to store a Json object using javascript, and retrieve it in python as i would like to store a sort of “shopping list” information that the user is generating, into my database. The object appears in my browsers session storage

enter image description here

but it seems my syntax is off as im getting “KeyError: ‘routine'”

 @app.route("/workoutroutines", methods=["GET", "POST"])
def showWorkoutRoutines():
    """Show all workout routines, allow user to create new routine"""
    
    if session['routine'] is not None: // <---error here
       try: 
        obj = json.loads(session['routine'])
        print(obj.name) 
     
       except: 
           print("something went wrong")
        



    all_routines = WorkoutRoutines.query.all()
    createRoutineButton = url_for("createARoutine")
    return render_template("allRoutines.html", all_routines=all_routines, createRoutineButton=createRoutineButton)

error log:

Traceback (most recent call last):
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 2088, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 2073, in wsgi_app
    response = self.handle_exception(e)
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflaskapp.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:UsersuserDesktopSpringboardworkoutAppapp.py", line 171, in showWorkoutRoutines
    if session['routine'] is not None:
  File "C:UsersuserDesktopSpringboardworkoutAppvenvLibsite-packagesflasksessions.py", line 79, in __getitem__
    return super().__getitem__(key)
KeyError: 'routine'

Advertisement

Answer

You’re getting a key error because when you write

session['routine']

Your code is trying to access the key ‘routine’ in the session object but it’s not there, so it’s throwing a key error.

You could modify it to:

if 'routine' in session:
    obj = json.loads(session['routine'])
    print(obj) 
else:
    print('your error message')

Within flask you can also see what keys are in the session object by doing:

app.logger.info('Session keys: {}'.format(session.keys()))

I don’t think flask logs stuff at info level by default, so for this to work you need to set logging to info level when you start your app. If that’s too fiddly just replace ‘app.logger.info’ with print.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement