【问题标题】:KeyError: 'user' when I use sessions with templates (jinja) - Python FlaskKeyError:'用户'当我使用带有模板的会话(jinja) - Python Flask
【发布时间】:2021-06-01 10:07:00
【问题描述】:

我正在尝试制作一个简单的模板导航栏,告诉未登录的用户登录或注册,并告诉登录的用户注销,但是当我这样做时出现“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")

我知道登录路径非常简单,但现在我只想让登录系统正常工作。

编辑:我可以补充一下,它在 session['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'

【问题讨论】:

    标签: python templates flask session jinja2


    【解决方案1】:

    错误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 是一个辅助函数,仅当字典对象中不存在键值时才将键值附加到字典对象中,否则它将简单地通过键更新值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2016-04-10
      相关资源
      最近更新 更多