重定向到同一页面后未显示Flask Flash消息

时间:2018-08-24 19:26:32

标签: python html flask

我有一个简单的网页,用户可以在该网页上从计算机中选择一个文件,然后按“上传”按钮,然后将以该文件作为输入来启动python脚本。

但是,我正在尝试获取它,以便如果用户上载会引发错误的文件,则Flash消息将显示在同一页面上(不进行任何重定向)。在我当前的尝试中,当我选择上传有目的的错误文件时,不会显示Flash消息。

另外,作为另一个问题,是否有可能(在app.py中)检查某些在我启动脚本后会出现的后端 python 错误消息(将在终端中显示的错误消息) )?

无论如何,这里是相关代码:

app.py:

@app.route("/", methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash("No file chosen", 'danger')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No selected file', 'danger')
            return redirect(request.url)
        elif not allowed_file(file.filename):
            flash('Incorrect file extenstion. Must be .TXT!', 'danger')
            return redirect(request.url)
        elif file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #
            # Process the file (omitted here)
            #

            proc = subprocess.Popen('python author_script.py {} -p {} -s {} -m {}'.format(file.filename, period, space, affiliation), shell=True, stdout=subprocess.PIPE)
            time.sleep(0.5)
            return redirect(url_for('results'))
        else:
            # THIS PART IS NOT WORKING!
            return redirect(request.path)
            flash('There is an affiliation missing from your Place list.', 'danger')
    return render_template('index.html', template_file=app.config['TEMPLATE_FILE'])

html模板(layout.html):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Author Script</title>
        <link rel="stylesheet" type="text/css" href="static/main.css" />
    </head>
    <body>
        {% include 'includes/_navbar.html' %}
        {% block body %}{% endblock %}
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ category }}">
                        {{ message }}
                    </div> 
                {% endfor %}
            {% endif %}
        {% endwith %}
        </div>

        <!-- Scripts -->
            <script src="js/jquery.min.js"></script>
            <script src="js/skel.min.js"></script>
            <script src="js/util.js"></script>
            <script src="js/main.js"></script>
    </body>
</html>

3 个答案:

答案 0 :(得分:1)

如果先执行Flash消息然后进行重定向,是否有帮助?像这样:

        flash('There is an affiliation missing from your Place list.', 'danger')
        return redirect(request.path)

编辑:

@app.route("/", methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
    if 'file' not in request.files:
        flash("No file chosen", 'danger')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No selected file', 'danger')
        return redirect(request.url)
    elif not allowed_file(file.filename):
        flash('Incorrect file extenstion. Must be .TXT!', 'danger')
        return redirect(request.url)
    elif file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        try:
            #
            # Process the file (omitted here)
            #

            proc = subprocess.Popen('python author_script.py {} -p {} -s {} -m {}'.format(file.filename, period, space, affiliation), shell=True, stdout=subprocess.PIPE)
            time.sleep(0.5)
            return redirect(url_for('results'))

        except Exception as e:
            print("type error: " + str(e)) # --> to answer your question on showing errors in console
            flash('There is an affiliation missing from your Place list.', 'danger')
            return redirect (request.path)
    return render_template('index.html', template_file=app.config['TEMPLATE_FILE'])

答案 1 :(得分:0)

要显示即显消息,您需要为其指定一个空格。可能您忘记为Flash消息添加空间。我鼓励您检查docs

您可以通过创建

messages.html

在其中粘贴以下代码

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    {% for category, message in messages %}
      <div class="alert alert-{{ category }}">{{ message }}</div>
    {% endfor %}
  {% endif %}
{% endwith %}

{% if error %}
  <div class="alert alert-danger">{{error}}</div>
{% endif %}

{% if msg %}
  <div class="alert alert-success">{{msg}}</div>
{% endif %}

确保在layout.html中调用此messages.html。像这样

{% include 'includes/_messages.html' %}

要使其更美丽,可以将其放在这样的位置

<div class='container'>
            {% include 'includes/_messages.html' %}
            {% block body %}{% endblock %}
        </div>

希望这可以解决您的问题。

最佳

答案 2 :(得分:0)

https://github.com/pallets/flask/issues/1168

此链接建议APPLCATION_ROOT的配置或缓存将解决/“修复”问题。首先尝试这些。

但是真正为我做的是在方法中添加get_flashed_message。

from flask import get_flashed_messages


@app.route('/')
def upload():
    get_flashed_messages()
    ....