Flask错误信息尽管设为none仍然存在

0 投票
1 回答
31 浏览
提问于 2025-04-14 17:13

我正在用Flask制作一个网站。这是我的 /login 页面:

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form.get('userName')
        password = request.form.get('userPassword')
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password_hash, password):
            return redirect(url_for('game'))
        else:
            error = 'Invalid username or password'
            return render_template('login.html', error=error)
    else:
        error = None
        return render_template('login.html', error=error)

如你所见,当用户成功输入他的账号和密码后,他会被重定向到 /game 页面。如果他输入的账号或密码错误,我会把 error 变量设置为 '无效的用户名或密码',并通过以下代码在登录页面上显示这个信息:

{% if error %}
    <div class="error">{{ error }}</div>
{% endif %}

不过,我现在遇到了一个很具体的问题,当用户按照以下步骤操作时:

  1. 用户输入错误的账号或密码,错误信息如预期出现
  2. 用户输入正确的账号和密码,然后被重定向到 '/game'
  3. 用户决定返回登录页面,并点击浏览器的后退箭头

在这种情况下,当用户返回到 /login 页面时,错误信息仍然显示着。我本以为可以通过把 error 设置为 None 来解决这个问题,但这样并没有效果。

任何帮助都会很感激。

1 个回答

0

为了防止这种情况发生,你可以告诉浏览器不要缓存登录页面。这样做的方法是添加一些响应头。下面是你登录功能的一个修改版,加入了这些响应头:

from flask import make_response

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        pass
    else:
        response = make_response(render_template('login.html', error=None))
        response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = '0'
        return response

这些响应头的作用是告诉浏览器不要缓存这个页面,这样当用户返回时,浏览器就会重新请求这个页面,确保错误信息被清除。

撰写回答