在烧瓶中使用Flash时如何仅显示唯一消息

时间:2018-07-06 17:36:46

标签: python flask

在烧瓶中使用flash功能时,我有两个功能。我叫f1,它叫f2 x次,叫f3 y次。我在f3中出现不一致的情况,因此我想在f3中进行刷新。但是,我不想再次将不一致性一直传递到f1,这导致以下事实:由于多次发生不一致,当前正在刷新消息多次。让用户知道1次就足以确定其原因。

所以我只想显示唯一的消息。

最小示例:

from flask import Flask, flash, render_template_string

app = Flask(__name__)
app.secret_key = 'arstarst'


@app.route('/')
def index():
    flash('banana', 'red')
    flash('apple', 'green')
    flash('banana', 'red')
    flash('pear', 'blue')
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% for category, message in messages %}
            <p style="color: {{category}}">{{message}}</p>
          {% endfor %}
      {% endif %}
    {% endwith %}
    ''')

1 个答案:

答案 0 :(得分:0)

解决方案:

  • 在神社中做出空洞的命令
  • 查看消息
  • 检查消息是否在字典中
  • 如果没有,添加到字典并打印消息
  • 如果是,则什么也不做

示例:

from flask import Flask, flash, render_template_string
app = Flask(__name__)
app.secret_key = 'arstarst'

@app.route('/')
def index():
    flash('banana', 'red')
    flash('apple', 'green')
    flash('banana', 'red')
    flash('pear', 'blue')
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% set printed_messages = dict() %}
          {% for category, message in messages %}
            {% if message not in printed_messages %}
              <p style="color: {{category}}">{{message}}</p>
              {% set x = printed_messages.__setitem__(message, "value")  %}
            {% endif %}
          {% endfor %}
      {% endif %}
    {% endwith %}
    ''')