Skip to main content
 首页 » 编程设计

python之Flask:忽略 'category' 参数的 Flash 函数

2025年05月04日17zhujiabin

所以我写了 Controller :

@app.route('/') 
def index(): 
    flash('Hello world!', 'success') 
    return render_template('index.html') 

然后在我的模板中输出这样的 flash 消息:

{%- with messages = get_flashed_messages(with_categories=true) -%} 
{%- if messages -%} 
    <ul class="flashes unstyled"> 
    {%- for category, message in messages -%} 
        <li class="alert alert-{{ category }}"> 
            <a class="close" data-dismiss="alert">&times;</a> 
            {{ message }} 
        </li> 
    {%- endfor -%} 
    </ul> 
{%- endif -%} 
{%- endwith %} 

但问题是我总是得到“消息”类别,所以 <li>上课'alert alert-message' .
我阅读了文档,对我来说我做的一切都是对的,但是 'flash'函数忽略第二个参数并始终使用默认值 'message' (而不是我给的“成功”)。

我想知道是否有人遇到过这个问题并且知道如何处理它?<​​/p>

请您参考如下方法:

编辑:根据其他评论,无需测试 kwarg。

基于 http://flask.pocoo.org/docs/api/#message-flashing 上的文档看来您需要使用这种格式。 flash(消息, category='message')

@app.route('/') 
def index(): 
    flash('Hello world!', category='success') 
    return render_template('index.html')