Flask Flash-сообщение не отображается после перенаправления на ту же страницу - PullRequest
0 голосов
/ 24 августа 2018

У меня есть простая веб-страница, где пользователь выбирает файл со своего компьютера, а затем нажимает кнопку «Загрузить», после чего сценарий python будет запущен с этим файлом в качестве ввода.

Однако,Я пытаюсь сделать так, чтобы, если пользователь загружает файл, который выдаст ошибку, 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>

Ответы [ 2 ]

0 голосов
/ 31 августа 2018

Чтобы показывать флеш-сообщения, вам нужно указать для этого место. Возможно, вы забыли добавить место для флеш-сообщений. Я рекомендую вам проверить документы .

Вы можете сделать это, создав

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 %}

Убедитесь, что вы вызываете этот messages.html внутри layout.html. Как это

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

, чтобы сделать его более красивым, вы можете поместить его вот так

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

Надеюсь, это решит вашу проблему.

Best

0 голосов
/ 24 августа 2018

Поможет ли вам сначала сделать флэш-сообщение, а затем перенаправить?Как это:

        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'])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...