KeyError: 'user' when I use sessions with templates (jinja) - Python Flask
KeyError: 'user' when I use sessions with templates (jinja) - Python Flask
我正在尝试制作一个简单的模板导航栏,告诉未登录用户登录或注册,并告诉登录用户注销,但我收到“KeyError:'user'”我这样做时出错。我不知道为什么会这样,因为这之前对我有用。
如果有人能帮助指导我,那将不胜感激!
模板
{% if session['logged_in'] %}
<a href="/logout" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">Log out</a>
<a href="#" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">{{SESSION_USERNAME}}</a>
{% else %}
<a href="#" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">Login / Signup</a>
{% endif %}
模板路由
@app.route('/')
def index():
return render_template('index.html', PAGE_TITLE = "Home :: ImageHub", SESSION_USERNAME=session['user'])
登录路径
@app.route('/login', methods=["POST", "GET"])
def login():
if(request.method == "POST"):
username = request.form['input-username']
password = request.form['input-password']
user = db.users.find_one({'username': username, 'password': password})
session['user'] = user['username']
session['logged_in'] = True;
return redirect(url_for('index'))
elif(request.method == "GET"):
return render_template('login.html', PAGE_TITLE = "Login :: ImageHub")
我知道登录路径非常简单,但现在我只想让登录系统正常工作。
编辑:我可以补充一下,它在会话['logged_in'] 设置为 true 时有效,但在弹出时中断。
错误
[2021-05-31 17:23:24,850] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Github Repositories\Repositories\Imagehub\server.py", line 17, in index
return render_template('index.html', PAGE_TITLE = "Home :: ImageHub", SESSION_USERNAME=session['user'])
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\werkzeug\local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\sessions.py", line 84, in __getitem__
return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'user'
错误KeyError: 'user'
表示您的会话对象不包含键user
。在您的 EDIT 部分,问题是相同的,您缺少字典对象中的键。您需要将 user
键添加到您的会话对象:
def add_to_dict(dict_obj, key, value):
# Check if key exist in dict or not
if key in dict_obj:
# Key exist in dict.
# Check if type of value of key is list or not
if not isinstance(dict_obj[key], list):
# If type is not list then make it list
dict_obj[key] = [dict_obj[key]]
# Append the value in list
dict_obj[key].append(value)
else:
# As key is not in dict,
# so, add key-value pair
dict_obj[key] = value
@app.route('/login', methods=["POST", "GET"])
def login():
if(request.method == "POST"):
username = request.form['input-username']
password = request.form['input-password']
user = db.users.find_one({'username': username, 'password': password})
# You probably want to do some checks on user object here :)
add_to_dict(session, 'user', user['username'])
add_to_dict(session, 'logged_in', True)
return redirect(url_for('index'))
elif(request.method == "GET"):
return render_template('login.html', PAGE_TITLE = "Login :: ImageHub")
add_to_dict
是一个辅助函数,如果字典对象中不存在键值,它只会将键值附加到字典对象,否则它只会通过键更新值。
我正在尝试制作一个简单的模板导航栏,告诉未登录用户登录或注册,并告诉登录用户注销,但我收到“KeyError:'user'”我这样做时出错。我不知道为什么会这样,因为这之前对我有用。
如果有人能帮助指导我,那将不胜感激!
模板
{% if session['logged_in'] %}
<a href="/logout" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">Log out</a>
<a href="#" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">{{SESSION_USERNAME}}</a>
{% else %}
<a href="#" class="w3-bar-item w3-button w3-hover-none w3-text-light-grey w3-hover-text-light-grey w3-right">Login / Signup</a>
{% endif %}
模板路由
@app.route('/')
def index():
return render_template('index.html', PAGE_TITLE = "Home :: ImageHub", SESSION_USERNAME=session['user'])
登录路径
@app.route('/login', methods=["POST", "GET"])
def login():
if(request.method == "POST"):
username = request.form['input-username']
password = request.form['input-password']
user = db.users.find_one({'username': username, 'password': password})
session['user'] = user['username']
session['logged_in'] = True;
return redirect(url_for('index'))
elif(request.method == "GET"):
return render_template('login.html', PAGE_TITLE = "Login :: ImageHub")
我知道登录路径非常简单,但现在我只想让登录系统正常工作。
编辑:我可以补充一下,它在会话['logged_in'] 设置为 true 时有效,但在弹出时中断。
错误
[2021-05-31 17:23:24,850] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Github Repositories\Repositories\Imagehub\server.py", line 17, in index
return render_template('index.html', PAGE_TITLE = "Home :: ImageHub", SESSION_USERNAME=session['user'])
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\werkzeug\local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\sessions.py", line 84, in __getitem__
return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'user'
错误KeyError: 'user'
表示您的会话对象不包含键user
。在您的 EDIT 部分,问题是相同的,您缺少字典对象中的键。您需要将 user
键添加到您的会话对象:
def add_to_dict(dict_obj, key, value):
# Check if key exist in dict or not
if key in dict_obj:
# Key exist in dict.
# Check if type of value of key is list or not
if not isinstance(dict_obj[key], list):
# If type is not list then make it list
dict_obj[key] = [dict_obj[key]]
# Append the value in list
dict_obj[key].append(value)
else:
# As key is not in dict,
# so, add key-value pair
dict_obj[key] = value
@app.route('/login', methods=["POST", "GET"])
def login():
if(request.method == "POST"):
username = request.form['input-username']
password = request.form['input-password']
user = db.users.find_one({'username': username, 'password': password})
# You probably want to do some checks on user object here :)
add_to_dict(session, 'user', user['username'])
add_to_dict(session, 'logged_in', True)
return redirect(url_for('index'))
elif(request.method == "GET"):
return render_template('login.html', PAGE_TITLE = "Login :: ImageHub")
add_to_dict
是一个辅助函数,如果字典对象中不存在键值,它只会将键值附加到字典对象,否则它只会通过键更新值。