Often times, you will want to have a nice and simple way to send and display small messages to your users. Maybe it's just a simple message telling them they have successfully logged in, or maybe it is a message that pops up to notify them that they have a private message. Or maybe you want to notify your users about a short down-time that is coming for a server restart. Who knows, I am sure you can think of many reasons why you might want to send a quick message to your users.
There are many ways you could do this, but Flask actually has a built in functionality just for this task: Flash.
The nifty thing about Flash is the message you choose to flash is stored, and, once the message is passed once, it is removed from the list of messages to flash. If for whatever reason the flash is not shown (maybe you have a page that doesn't handle the flash), then it will be held until it is finally flashed to the user.
I find the best place and way to handle flashes is to by the Jinja templating logic to handle the flash in the header.html file, this way it is automatically on all of your pages, and appears just before the content of the page, but under the navbar. You can of course choose as you please where to put it.
from flask import Flask, render_template, flash from content_management import Content ... @app.route('/dashboard/') def dashboard(): flash("flash test!!!!") flash("fladfasdfsaassh test!!!!") flash("asdfas asfsafs!!!!") return render_template("dashboard.html", TOPIC_DICT = TOPIC_DICT)
Looking at our dashboard here, we can see that we've included a few of these flash("messages").
Since flash is a part of Flask, we had better import it as well.
This is all we need with our init file, now we just need to handle flashes in our header template.
Here not much has changed, besides the logic starting with the
with messages = get_flashed_messages().
Like I was saying before, we actually do not need to do anything but call the flash function when we wish to flash a message, and we do not need to pass it to the HTML, since it is built into flask, and it will be passed on its own.
From here, the logic is relatively self-explanitory, where we are first calling the get_flashed_messages() function. With the result of that, we're checking to see if there are any messages. If so, we then iterate through them with a for loop.
Now that we can pass messages to our users, we can of course pass messages based on what the user does, but what if we want to pass a message to a specific user? Sounds like we need a user system.