python - 在 Flask 中使用 session 时出现 KeyError

标签 python flask

因此,我尝试使用 Flask 将值从一个 html 页面传递到另一个 html 页面。我编写的代码如下所示:

from flask import Flask, render_template
from flask import request, session, url_for,abort,redirect

app = Flask(__name__)

app.config['SECRET_KEY'] = 'oh_so_secret'


@app.route('/'):
def first():
    session['this_one']='hello'
    render('template.html')

@app.route('/second')
def second():
   it=session['this_one']
    render('other_page.html')

if __name__ == '__main__':
    app.run(debug=True)

但是当我运行它时,我得到一个 KeyError:this_one

所以,它今天工作,重新启动系统。然后我做了一些改变:

@app.route('/'):
def first():
    session['this_one']='goodbye'
    render('template.html')

@app.route('/second')
def second():
   it=session['this_one']
   render('other_page.html')

第二个函数仍然返回hello

所以看起来 session 字典并没有像我希望的那样被覆盖。

跟进

这是一个真正的谜,它在没有进行任何更改的情况下,前一天有效,后一天就失效了。现在在溃败 ('/') 我正在设置一个列表:

@app.route('/'):
def first():
    session['this_one']='hello'
    session['a_list']=['a','b','c']
    render('template.html')

在第二个函数中使用打印命令调用它:

@app.route('/second')
def second():
    it=session['this_one']
    print(session['a_list'])
    render('other_page.html')

并返回一个空列表[]

最佳答案

您的代码运行良好(除了缩进问题,我认为这是此处的错别字,而不是实际代码中的错别字)。必须发生的是第二页在第一页之前被访问。您可以使用异常处理来检查 KeyError 并在遇到时重定向到第一页。

关于python - 在 Flask 中使用 session 时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32231183/

相关文章:

python - 如何在 TF Lite 中添加预处理步骤

python - 带函数返回的 Flask render_template

python - 使用应用程序工厂时在 pytest 测试中访问 Flask 测试客户端 session

python - SQLAlchemy 快速搜索

python - 使用 Flask 进行简单的日志过滤

python - 如何在Colab中播放视频?

python - 使用 Poetry 在 Python 项目中执行自定义命令

python - 尝试使用 Pandas 计算百分比并添加新列

python - DBSCAN sklearn 非常慢

javascript - 如何使用 javascript 绘制之前保存在 docker workdir 中的图像?