Flask Flash function Tutorial




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.

Because Flash is built into Flask as well, you wont actually need to pass the "flash" through the templates. It will already be there and you need not reference it as a parameter for every template, which is nice! Finally, we can combine the flash functionality with Bootstrap's javascript to make the message close-able on the page as well! Let's do 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.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Python Programming Tutorials</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
	<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>

<header>
	<div class="navbar-header">
      <a class="navbar-brand" href="/">
	  <img style="max-width:120px; margin-top: -7px;" src="{{ url_for('static', filename='images/mainlogo.png') }}">
	  </a>
    </div>
	
	
	<div class = "container-fluid">

		<a href="/dashboard/"><button type="button" class="btn btn-primary" aria-label="Left Align" style="margin-top: 5px; margin-bottom: 5px; height: 44px; margin-right: 15px">
		  <span class="glyphicon glyphicon-off" aria-hidden="true"></span> Start Learning
		</button></a>

	<ul class="nav navbar-nav navbar-right">
		  <div style="margin-right: 10px; margin-left: 15px; margin-top: 5px; margin-bottom: 5px;"  class="container-fluid">
			<a href="/support-donate/"> <span class="glyphicon glyphicon-heart"></span> Support   </a>
			<a href="/login/"><span class="glyphicon glyphicon-log-in"></span> Login   </a>
		<a href="/register/"><span class="glyphicon glyphicon-pencil"></span> Sign up</a><h5>
	  </div>
      </ul>
	</div>

</header>

<body>

	<div class="container" style="min-height:100% width:80%">
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
	    {% for message in messages %}
		  <div class="alert alert-warning alert-dismissible" role="alert">
		  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
			{{message}}
		  </div>
		{% endfor %}
	  {% endif %}
	{% endwith %}
	
	{% block body %}{% endblock %}
	</div>

	<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>

</body>

</html>
		

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.

Then, we use the div class of "alert," which is part of Bootstrap. From there, we add a nice little button (again, Bootstrap!), and we even give this button the ability to dismiss the message, which will make it disappear thanks to a nice little javascript function, which, again, is all thanks to Bootstrap!

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.

The next tutorial:





  • Introduction to Practical Flask
  • Basic Flask Website tutorial
  • Flask with Bootstrap and Jinja Templating
  • Starting our Website home page with Flask Tutorial
  • Improving the Home Page Flask Tutorial
  • Finishing the Home Page Flask Tutorial
  • Dynamic User Dashboard Flask Tutorial
  • Content Management Beginnings Flask Tutorial
  • Error Handling with Flask Tutorial
  • Flask Flash function Tutorial
  • Users with Flask intro Tutorial
  • Handling POST and GET Requests with Flask Tutorial
  • Creating MySQL database and table Flask Tutorial
  • Connecting to MySQL database with MySQLdb Flask Tutorial
  • User Registration Form Flask Tutorial
  • Flask Registration Code Tutorial
  • Finishing User Registration Flask Tutorial
  • Password Hashing with Flask Tutorial
  • Flask User Login System Tutorial
  • Decorators - Login_Required pages Flask Tutorial
  • Dynamic user-based content Flask Tutorial
  • More on Content Management Flask Tutorial
  • Flask CMS Concluded Flask Tutorial
  • The Crontab Flask Tutorial
  • Flask SEO Tutorial
  • Flask Includes Tutorial
  • Jinja Templating Tutorial
  • Flask URL Converters Tutorial
  • Flask-Mail Tutorial for email with Flask
  • Return Files with Flask send_file Tutorial
  • Protected Directories with Flask Tutorial
  • jQuery with Flask Tutorial
  • Pygal SVG graphs with Flask Tutorial
  • PayPal with Flask Web Development Tutorial
  • Securing your Flask website with SSL for HTTPS using Lets Encrypt