简体   繁体   中英

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

在此处输入图片说明

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:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 2088, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:\Users\user\Desktop\Springboard\workoutApp\app.py", line 171, in showWorkoutRoutines
    if session['routine'] is not None:
  File "C:\Users\user\Desktop\Springboard\workoutApp\venv\Lib\site-packages\flask\sessions.py", line 79, in __getitem__
    return super().__getitem__(key)
KeyError: 'routine'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM