使用 Flask 显示多条 Flash 消息

Displaying multiple flash messages with flask

我正在尝试使用 flask 在我的 html 上显示多个 flash 消息,以解决验证表单可能出现的任何错误。现在只有一个。有没有办法做到这一点?可能是错误消息进入的某种空白列表,然后在 html 侧遍历该列表?

python:

@app.route("/user", methods=['POST'])

def create_user():

    if len(request.form["name"]) < 1:
        flash("Name cannot be blank")
        return redirect("/")
    else:
        session["name"] = request.form["name"]
        session["location"] = request.form["location"]
        session["language"] = request.form["language"]
    if len(request.form["comment"]) > 120:
        flash("Comment cannot be longer than 120 characters")
        return redirect("/")
    elif len(request.form["comment"]) < 1:
        flash("Comment cannot be blank")
    else:
        session["comment"] = request.form["comment"]

    return redirect("/results")

html:

{% with messages = get_flashed_messages() %}
    {% if messages %}
        {% for message in messages %}
            <p>{{ message }}</p>
        {% endfor %}
    {% endif %}
{% endwith %}
<form action="/user" method="POST" accept-charset="utf-8">
    <label>Name:</label>
    <div id=right>
        <input type="text" name="name">
    </div>
    <label>Location:</label>
    <div id=right>
        <select name="location">
        <option value="location1">Location 1</option>
        <option value="location2">Location 2</option>
        </select>
    </div>
    <label>Language:</label>
    <div id=right>
        <select name="language" >
        <option value="choice1">Choice 1</option>
        <option value="choice2">Choice 2</option>
        </select>
    </div>
    <label>Comment (optional):</label>
    <textarea name="comment" rows="5", cols="35"></textarea>
    <button type="submit">Submit</button>
</form>

您绝对可以显示多个即显消息,这是默认行为。问题是您的代码路径永远不允许多个 flash 消息,因为您在调用 flash 后立即返回 redirect。您可以像这样重构您的代码:

@app.route("/user", methods=['POST'])

def create_user():

    errors = False

    if len(request.form["name"]) < 1:
        flash("Name cannot be blank")
        errors = True
    else:
        session["name"] = request.form["name"]
        session["location"] = request.form["location"]
        session["language"] = request.form["language"]

    if len(request.form["comment"]) > 120:
        flash("Comment cannot be longer than 120 characters")
        errors = True
    elif len(request.form["comment"]) < 1:
        flash("Comment cannot be blank")
        errors = True
    else:
        session["comment"] = request.form["comment"]

    if errors:
        return redirect("/")
    else:
        return redirect("/results")