You are on your way to becoming a first-class developer! Don't get overexcited, though. A lot of new and fascinating things lie ahead. Today, we will talk about redirects and flash messages. They can improve your app, guide users, show a notification, and so on. Let's get it started!
Redirects
Let's cover the redirect first. We need it to send users to another page in a forced manner. Let's take a simple example. You go to YouTube, click on the login button, enter your username and password, and... you are brought back to the main page. The magic in action! Let's take a look at how it works in practice.
As usual, we need to import necessary objects and initialize the app. After that, we create two view functions so that one redirects to another. To do this, use the redirect method to return a value:
from flask import Flask, redirect
app = Flask('main')
@app.route('/')
def main_view():
return "Hello, it's the Main Page!"
@app.route('/redirector')
def redirect_view():
return redirect('/')
app.run()The redirect method is rather simple. We pass a string that specifies the destination URL; that's it. It has several additional arguments, but we won't talk about them for now. You can find the exhaustive list in the official Flask documentation.
Good! Now, let's start our program and see how it works. First, go to the root:
When you go to /redirector, the site redirects you to the main page! That's how the redirect works: specify the URL, and a site or app will bring you to it:
You can use this method to redirect users to the home page after authorization, a placeholder for mail confirmation, and so on. The method is extremely handy.
Flash messages
What do you know about flash messages? If not much, we have something for you — flashes (also known as pop-ups) are notifications in a browser. Flash messages are saved after redirection. For example, users log in to our site, and we immediately send them a flash with a message that the login was successful. After that, we redirect them to the main page, and the flash message remains there. Let's take a look at the implementation. As usual, we must import methods and objects first:
from flask import Flask, flash, get_flashed_messages
app = Flask('main')After that, we need to specify the secret key. It allows us to use flashes:
app.config['SECRET_KEY'] = 'So-Seckrekt'And now we should define two view functions. The main page view function is conventional:
@app.route('/')
def main_view():
return "Hello, it's the Main Page!"But the second one is more intriguing. That's where we use something new! Take a look:
@app.route('/not_ready')
def redirect_view():
flash('This page is not ready yet! Return later!')
return get_flashed_messages()[0]The flash method sends a message with the specified text, and the get_flashed_messages function returns a list of all flashed messages. This is a simple way to inform or warn your users. Now, it is time to start your app with app.run() and bring your creation to light! Your main page:
If you go to /not_ready, Flask will send you a flash message that says This page is not ready yet! Return later! This is exactly what we wanted.
Improved flashes
Flashes can have an additional argument, a category. You can pass it to the flash method to indicate that the message belongs to a specific type. It can be a string, but it should convey the essence of the message. For example, if you want to notify users that they are looking at the site for 5 hours straight, you can use the info category. If you want to tell your users that they don't have the right to do something, use error.
This is pretty easy to implement by adding a second argument to the flash function:
flash('You are hanging around on our site for more than 5 hours. Maybe, you need a break', 'info')Categories can help you separate notifications and show them in the right place with the right label. Now, we will need our template writing skills. Now, try to use all Flask skills to create a page with the basic template, base.html. Let's try it!
First, let's see how base.html looks like:
<!doctype html>
<title>Super-App</title>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}This is a standard HTML document. We specify the name of the web page, Super-App, and then use loops to display the messages together with their categories.
Now, let's create another template — main.html. It is our home page:
{% extends "base.html" %}
{% block body %}
<h1>Welcome to the best website in the world, the galaxy, and all of our reality!</h1>
{% endblock %}Once everything is ready, we can switch back to Python. After import and app initialization, we create a view function for the main page and launch the app:
from flask import Flask, flash, redirect, get_flashed_messages
app = Flask('main')
@app.route('/')
def main_view():
flash('You hang on our site for more than 5 hours in a row. Take a break, please.', 'info')
return render_template('main.html')
app.run()We'll see the main page with a notification on the top:
The last thing we would like to mention is the get_flahed_messages method. It has a very useful argument: category_filter. This argument is a list that contains all message categories. For example, if you want to get only informational flashes under the info category, you can do the following:
get_flashed_messages(category_filter=['info'])Conclusion
We have learned the basics of redirects and flashes. Now, we know how to incorporate them into an application. To sum up, redirects can be used to lead users to a specific page, different from the initial one. Flashes, in their turn, can show users messages and notifications. Down with the theory; let's go and practice!