Skip to content Skip to sidebar Skip to footer

How To Display Flashing Message Without Reloading The Page In Flask?

I'm working on a web application using Flask in Python. I have small function in my application that calculates some values in the background and displays the result on the web pa

Solution 1:

Here's what Flask Web Development: Developing Web Applications with Python (pp. 46-48) has to say of Message Flashing:

Sometimes it is useful to give the user a status update after a request is completed. This could be a confirmation message, a warning, or an error. A typical example is when you submit a login form to a website with a mistake and the server responds by rendering the login form again with a message above it that informs you that your username or password is invalid. Flask includes this functionality as a core feature. Example 4-6 shows how the flash() function can be used for this purpose.

Example 4-6. hello.py: Flashed messages

@app.route('/', methods=['GET', 'POST'])defindex():
    form = Nameform()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name isnotNoneand old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        form.name.data = ''return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))
        form = form, name = session.get('name'))

In this example, each time a name is submitted it is compared against the name stored in the user session, which would have been put there during a previous submission of the same form. If the two names are different, the flash() function is invoked with a message to be displayed on the next response sent back to the client.

Calling flash() is not enough to get messages displayed; the templates used by the application need to render these messages. The best place to render flashed messages is the base template, because that will enable these messages in all pages. Flask makes a get_flashed_messages() function available to templates to retrieve the messages and render them, as shown in Example 4-7.

Example 4-7. templates/base.html: Flash message rendering

{% block content %}
<divclass="container">
    {% for message in get_flashed_messages() %}
    <divclass="alert alert-warning"><buttontype="button"class="close"data-dismiss="alert">&times;</button>
        {{ message }}
    </div>
    {% endfor %}

    {% block page_content %}{% endblock %}
</div>
{% endblock %}

In this example, messages are rendered using Bootstrap’s alert CSS styles for warning messages (one is shown in Figure 4-4).

Figure 4-4. Flashed message

Figure 4-4. Flashed message

A loop is used because there could be multiple messages queued for display, one for each time flash() was called in the previous request cycle. Messages that are retrieved from get_flashed_messages() will not be returned the next time this function is called, so flashed messages appear only once and are then discarded.

Solution 2:

This is not possible via Python without reloading the page. You must do this in javascript. I suggest CSS styling with display: none and display: block. Here is an example.

1) Python Code, this should go in your app.py or flask.py file.

app.route('/flash/<message>')
defflash(message):
  return render_template('flash.html', msg=message)

This will render the HTML page named flash.html. The URL passed in will also have another argument, <message> this is the message that will flash. A URL like this, localhost:80/flash/Hello%20World! will flash the message "Hello World!" on your screen.

There is also another way to pass a message in, this is will arguments. The code for that is like so.

app.route('/flash')
def flash():
  message = request.args.get("msg")
  return render_template("flash.html", ,msg=message)

This uses the flask's request arguments. So a URL like this, localhost:80/flash?msg=Hello%20World! will give a flashing message saying "Hello World!". If you want to use this method be sure to have the import statement, from flask import request in your import statements.

2) Html Code, this is a separate file named, flash.html in your templates folder.

<body><h1id="header">{{ message }}</h1><script>var heading = $("#header");
    setInterval(function() {
      if (heading.style.display == "block") { heading.style.display = "none"; }
      elseif (heading.style.display == "none") { heading.style.display = "block"; }
    }, 1000);
  </script></body>

The 1000 in the setInterval is milliseconds. So the heading will blink every 2 seconds.

Solution 3:

You may want to consider using Toastr instead. I ran into the same roadblock with Flask's Flash feature, and Toastr is pure JS. You can use it just like a console log line in your code

toastr.info("Here's a message to briefly show to your user");

Post a Comment for "How To Display Flashing Message Without Reloading The Page In Flask?"