JavaScript存储在会话中,从python/flask中的会话中获取

2022-03-10 00:00:00 python flask flask-sqlalchemy

问题描述

我正在使用一个flask应用程序,正在尝试使用javascript存储一个Json对象,并在python中检索它,因为我希望将用户正在生成的购物清单和信息存储到我的数据库中。该对象出现在我的浏览器会话存储中

但似乎我的语法不正确,因为我收到了";KeyError:‘例程’

 @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)

错误日志:

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'

解决方案

您收到一个键错误,因为当您写入

session['routine']

您的代码正在尝试访问Session对象中的键"例程",但它不在那里,所以它引发了键错误。

您可以将其修改为:

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

在flask中,您还可以通过执行以下操作查看会话对象中的密钥:

app.logger.info('Session keys: {}'.format(session.keys()))
我认为flask在默认情况下不会记录信息级别的内容,因此要使其正常工作,您需要在启动应用程序时将日志记录设置为信息级别。如果这太麻烦了,只需将"app.logger.info"替换为print即可。

相关文章