【问题标题】:Flask: Include HTML in a return render_template() or redirect()Flask:在返回 render_template() 或 redirect() 中包含 HTML
【发布时间】:2017-03-16 13:51:26
【问题描述】:

我有一个登录表单,用于检查用户提供的用户名和密码是否在数据库中返回一行。如果是,则存储会话 cookie,并将用户发送回索引页面。如果没有,用户将再次返回登录页面。

这是相关代码的sn-p:

cur.execute("SELECT COUNT(*) FROM users WHERE username = ? AND password = ?", (request.form['username'], request.form['password']))

data = cur.fetchone()[0]

# If given username and password returns a row, create the session
if data == 0:
    return redirect(url_for('index'))
else:
    session['username'] = request.form['username']

当用户再次返回登录页面 (redirect(url_for('index'))) 时,我想在登录页面上包含一条消息,说明给定的用户名或密码无效。

我对如何准确地做到这一点有点迷茫。

【问题讨论】:

    标签: python flask sqlite


    【解决方案1】:

    这称为消息闪烁。完整的文档是here,它是通过在视图端添加消息然后在模板上呈现它们来完成的,如下所示:

    <!doctype html>
    <title>My Application</title>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    {% block body %}{% endblock %}
    

    【讨论】:

    • 这正是我所需要的。谢谢!
    【解决方案2】:

    http://flask.pocoo.org/docs/0.10/patterns/flashing/ 结帐flash。那应该做你想做的事。只需处理 index 模板中的 flash 消息!

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2017-12-03
      • 2018-09-12
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多