How To Use Flash Messages In Python Flask

How To Use Flash Messages In Python Flask

Flash messages are used in web applications to provide helpful feedback to users as they navigate a graphical user interface. You are likely familiar with flash messages if you have ever signed up for an account with any of the popular services available on the Internet today. These messages typically appear one time for a given event and disappear after a short period of time with the help of some simple JavaScript code. In this tutorial, we’ll see how to generate such flash messages in a Python Flask application.


flash() – Setting The Flash Message

To create a flash message in Flask, you can use the flash module by importing it into your project. The flash() function is passed a message argument and an optional category argument. The highlighted line of code below adds a flash message to our Flask application.

from flask import Flask, render_template, request, redirect, url_for, flash
import json
import os.path

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
    if request.method == 'POST':
        urls = {}
        if os.path.exists('urls.json'):
            with open('urls.json') as url_storage:
                urls = json.load(url_storage)
        if request.form['shortcode'] in urls.keys():
            flash('Please choose a different Shortcode, that one is already in use')
            return redirect(url_for('home'))
        urls[request.form['shortcode']] = request.form['url']
        with open('urls.json', 'w') as url_storage:
            json.dump(urls, url_storage)
        return render_template('shortenurl.html', shortcode=request.form['shortcode'])
    elif request.method == 'GET':
        return redirect(url_for('home'))
    else:
        return 'Not a valid request method for this route'


@app.route('/<string:shortcode>')
def shortcode_redirect(shortcode):
    if os.path.exists('urls.json'):
        with open('urls.json') as url_storage:
            urls = json.load(url_storage)
            if shortcode in urls.keys():
                return redirect(urls[shortcode])

Now if you try to run the code right away, you’ll get an error such as: “RuntimeError RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.” So in order to use flash messages in Flask, you need a secret key to be set. Let’s do that now.


Add Secret Key

As mentioned above we’re using message flashing so we have to add one more attribute into the flask app. This can be done inside of app.py just after the app variable is set. The way to do this is with app.secret_key. This allows us to securely send messages back and forth from the user to make sure there can be no spooning on the connection and the information cannot be seen. So we need to provide some sort of random string for the app.secret_key and because we’re in development, you can just type some imaginary string. When it comes to production, you would want to find a very random key and make it long so that no one could guess the secret key.


get_flashed_messages() – Getting The Flash Message

At this point, the message is getting flashed to the session, but we will not see anything on the GUI. The way that flash messages work in a Flask application is to pass forward any flash message to the template that you’re about to render. Inside of that template, you can check and see if there are any flash messages and if there are, display them to the user.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Make A Short URL</title>
</head>
<body>
<h1>Make A Short URL</h1>
{% for message in get_flashed_messages() %}
<h2>{{ message }}</h2>
{% endfor %}
<form action="shortenurl" method="post">
    <label for="url">Enter URL</label>
    <input type="url" name="url" value="" required>
    <label for="shortcode">Enter Name</label>
    <input type="text" name="shortcode" value="" required>
    <input type="submit" value="Submit">
</form>

</body>
</html>

Now that we have used flash() in app.py, set an app.secrect_key, and also added the call to the get_flashed_messages() in the template, the user should see a flash message if there is a duplicate shortcode already found in our JSON file. Sure enough, it is working great!

Learn More About How To Use Flash Messages In Python Flask