Python 获得;KeyError:';示例'&引用;在不同路由中读取会话值时
我有一个问题,因为我想在会话中包含值。当我在一个Python 获得;KeyError:';示例'&引用;在不同路由中读取会话值时,python,session,flask,Python,Session,Flask,我有一个问题,因为我想在会话中包含值。当我在一个app.route中保存这些值,然后我需要转到另一个链接并使用该值时,我会得到一个KeyError。我做错了什么 from flask import Flask, render_template, request, session from OPTYMALIZACJA import OPTYMALIZACJA app = Flask(__name__) app.secret_key = "abc" app.config[
app.route
中保存这些值,然后我需要转到另一个链接并使用该值时,我会得到一个KeyError
。我做错了什么
from flask import Flask, render_template, request, session
from OPTYMALIZACJA import OPTYMALIZACJA
app = Flask(__name__)
app.secret_key = "abc"
app.config['SESSION_TYPE'] = 'memcached'
@app.route('/', methods=['POST', 'GET'])
def first():
# calculation instructions
session['example'] = 'example1'
return render_template('index.html')
@app.route('/export')
def second():
s = session['example']
print(s)
return render_template('index.html')
在
index.html
中,我有一个指向localhost/export
页面的链接。您的代码对我来说是有效的,通常使用get
来防止类似的键错误是一种很好的做法,所以不要使用s=session['example']
dos=session get('example',default value')
从烧瓶导入烧瓶,会话
app=烧瓶(名称)
app.secret_key=“abc”
app.config['SESSION_TYPE']='memcached'
@app.route('/',方法=['POST','GET'])
def first():
#计算说明
会话['example']=“example1”
返回会话['example']
@app.route(“/export”)
def second():
s=session.get('example','yourdaultvaluehere')
印刷品
返回会话['example']
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run()
您发布的代码按预期工作
以下是一些您可以检查的内容:
会话
中第一次保存的密钥与在会话
中第二次保存的密钥完全相同。我知道您的示例代码已经显示了相同的键示例
,但是您的实际代码可能没有使用相同的键,或者是以某种方式从会话
中删除的
您可以通过打印session.items()
(如dict
)来检查会话的内容:
第一个
)。例如,当我测试您的示例代码时,我不小心刷新了/export,而没有访问位于/的正确路由print(session.items())
print(session['example'])
# 127.0.0.1 - - [12/Oct/2019 16:03:52] "GET /export HTTP/1.1" 200 -
# dict_items([('example', 'example1')])
# example1