Flask(十二)——消息闪现

一个基于GUI好的应用程序需要向用户提供交互的反馈信息。 例如,桌面应用程序使用对话框或消息框,JavaScript使用 alert() 函数用于类似的目的。


在Flask Web应用程序中生成这样的信息消息很容易。 Flask框架的闪现系统使得可以在一个视图中创建一个消息并将其呈现在名为 next 的视图函数中。

Flask模块包含 flash() 方法。 它将消息传递给下一个请求,该请求通常是一个模板。

flash(message, category)

在这里

  • message - 参数是要刷新的实际消息。
  • category - 参数是可选的。 它可以是’错误’,’信息’或’警告’。
    要从会话中删除消息,模板调用 get_flashed_messages() 函数。
get_flashed_messages(with_categories, category_filter)

两个参数都是可选的。 如果收到的消息具有类别,则第一个参数是元组。 第二个参数对于仅显示特定消息很有用。

以下闪现模板中收到消息。

{% with messages = get_flashed_messages() %}
    {% if messages %}
       {% for message in messages %}
          {{ message }}
       {% endfor %}
    {% endif %}
{% endwith %}

现在我们来看一个简单的实例,演示Flask中的闪现机制。 在下面的代码中,URL => / 显示了到登录页面的链接,没有指定要发送的消息。

@app.route('/')
def index():
    return render_template('index.html')

该链接引导用户显示登录表单的URL => /login。 提交时,login() 函数验证用户名和密码,并相应地闪现“成功”或“错误”变量消息。

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
                request.form['password'] != 'admin':
            error = 'Invalid username or password. Please try again!'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

如有错误,登录模板将重新显示并显示错误消息。

模板文件: login.html 代码如下

<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
      <h1>登录</h1>
       {% if error %}
       <p><strong>Error:</strong> {{ error }}
       {% endif %}
       <form action = "/login" method ="POST">
          <dl>
             <dt>用户名:</dt>
             <dd>
                <input type = text name = "username" 
                   value = "{{request.form.username }}">
             </dd>
             <dt>密码:</dt>
             <dd><input type ="password" name ="password"></dd>
          </dl>
          <p><input type = submit value ="登录"></p>
       </form>
    </body>
 </html>

如果登录成功,则在索引模板上闪现成功消息。以下代码保存在文件 index.html

<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask消息闪现</title>
 </head>
    <body>
          {% with messages = get_flashed_messages() %}
           {% if messages %}
             <ul class=flashes>
             {% for message in messages %}
               <li>{{ message }}</li>
             {% endfor %}
             </ul>
           {% endif %}
         {% endwith %}
       <h1>Flask Message Flashing Example</h1>
       <p>您想要<a href = "{{ url_for('login') }}">
          <b>登录?</b></a></p>
    </body>
 </html>

Flask 消息闪现示例的完整代码如下所示

from flask import Flask, flash, redirect, render_template, request, url_for

app = Flask(__name__)
app.secret_key = 'random string'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    print(request.method)
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
                request.form['password'] != 'admin':
            error = 'Invalid username or password. Please try again!'
        else:
            # flash('您已成功登录')
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)


if __name__ == "__main__":
    app.run(debug=True)

执行上述代码后,您将看到如下所示的屏幕。

当点击链接时,将会跳转到登录页面。输入用户名和密码

点击 登录 按钮。 将显示一条消息“您已成功登录”。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flask框架提供了闪现消息提示的功能,可以在请求之间传递消息。这些消息可以是成功或错误的消息,可以在下一个请求中显示给用户。闪现消息通常用于表单验证或用户登录后的欢迎消息等场景。 以下是一个简单的示例,演示如何使用闪现消息提示: ```python from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = 'some_secret_key' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': flash('登录成功!', 'success') return redirect(url_for('index')) else: flash('用户名或密码错误!', 'error') return render_template('login.html') if __name__ == '__main__': app.run(debug=True) ``` 在上面的示例中,我们首先导入了Flask框架和flash函数。然后,我们定义了一个应用程序,并设置了一个秘密密钥。接下来,我们定义了两个路由,一个用于显示主页,另一个用于处理登录请求。在登录路由中,我们首先检查请求的方法是否为POST,如果是,则获取用户名和密码。如果用户名和密码正确,则使用flash函数显示成功消息,并重定向到主页。否则,我们显示错误消息。 在HTML模板中,我们可以使用以下代码来显示闪现消息: ```html {% with messages = get_flashed_messages() %} {% if messages %} <ul class="flashes"> {% for message in messages %} <li class="{{ message[1] }}">{{ message[0] }}</li> {% endfor %} </ul> {% endif %} {% endwith %} ``` 在上面的代码中,我们首先使用get_flashed_messages函数获取所有闪现消息。然后,我们使用一个循环来遍历所有消息,并将它们显示为一个无序列表。每个消息都有一个类别,可以是success、error、warning或info。我们可以使用这些类别来为每个消息设置不同的样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值