Skip to main content
 首页 » 编程设计

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

2025年05月04日18wayfarer

因此,我尝试使用 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 并在遇到时重定向到第一页。