简体   繁体   English

烧瓶:在返回的render_template()或redirect()中包含HTML

[英]Flask: Include HTML in a return render_template() or redirect()

I have a login form that checks if the username and password given by the user returns a row or not in the database. 我有一个登录表单,用于检查用户提供的用户名和密码是否在数据库中返回一行。 If it does, then a session cookie is stored and user is sent back to the index page. 如果是这样,则将存储会话cookie,并将用户发送回索引页面。 If not, the user is sent back to the login page again. 如果不是,则将用户再次发送回登录页面。

Here's a snippet of the relevant code: 这是相关代码的片段:

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']

When the user is sent back to the login page again ( redirect(url_for('index')) ), I want to include a message on the login page saying that the given username or password is invalid. 当用户再次发送回登录页面( redirect(url_for('index')) )时,我想在登录页面上包含一条消息,指出给定的用户名或密码无效。

I'm a bit lost on how to do this exactly. 我对如何准确地执行此操作有些迷惑。

This is called Message Flashing. 这称为消息闪烁。 The full documentation is here , and it's done by adding the messages on the view side and then rendering them on template like this: 完整的文档在这里 ,它是通过在视图侧添加消息,然后将其呈现在模板上来完成的,如下所示:

<!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 %}

Checkout flash at http://flask.pocoo.org/docs/0.10/patterns/flashing/ . http://flask.pocoo.org/docs/0.10/patterns/flashing/上查看flash That should do what you want. 那应该做你想要的。 Just handle the flash messages in the template for index ! 只需处理index模板中的Flash消息即可!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM