Web development with python #6 : Use flash message and combine it with framework boostrap
Repository
What Will I Learn?
- Flash message
- Styling Flash message
Requirements
- Basic Python
- Install Python 3
- Install Flask
Resources
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Jinja2 -http://jinja.pocoo.org/docs/2.10/
- Bootstrap -https://getbootstrap.com/docs/3.3/getting-started/
Difficulty
Basic
Tutorial Content
I will continue my tutorial series on flasks, in the previous tutorial we have learned the basics of the flask and learned what we can do in the flask. You can follow the previous tutorial in the curriculum section. In this tutorial we will make an interaction with the user, we will give a feedback or response. We will make a flash to respond to input from the user, we just start this tutorial.
Flash message
For those of you who often develop a web, surely it will give a response when the user does something. for that, we can use help or features of the flash message. In this section, we will see how it applies to the flask.
- Import flash
to use flash we need to import the first one in our code. we can import it as follows:
import flash
from flask import flash
Now you can use the flash()
function. After importing it, I will use it when the login is successful.
- Make flash messages when logging in
We will use the flash message at certain times. In this section, we will make a flash message when the user successfully logs in. for that, we can see in routing /login
.
app.py
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
session['email'] = request.form['email']
flash("You have successfully logged in", "success")
return redirect(url_for('profileFunc', email = session['email']))
// if the user has logged in
if 'email' in session:
email = session['email']
return redirect(url_for('profileFunc', email = email))
return render_template('login.html')
Use flash: I use the flash message when I log in, so I can put it before redirecting to the profile page. the
flash ()
function has two mandatory parameters. The first parameter is the message that we will display and The second parameter is the type of the message used. There are several types of messages, they are info, success, warning. The example above is a function call before the page redirects to the profile menu, we will give a flash message like the followingflash("You have successfully logged in", "success")
.Redirect with flash: We have learned redirect in the flask in the previous tutorial, but how to redirect with flash message. We can display the message on the rederect page we are headed.
Show flash message on frontend
After importing and using it in the backend section, now to display in HTML elements. We will use the flash message on the profile page because we will redirect the page. We need a few lines of code like the following:
profile.html
<!DOCTYPE html>
<html>
<head>
<title>Template Jinja2</title>
</head>
<body>
{% with messages = get_flashed_messages() %} // Define variable
{% if messages %} // check if message exist
{% for message in messages %}
{{message}} // print out the message
{% endfor %}
{% endif %}
{% endwith %}
<h1>This is the profile page</h1>
<h2 style="color:blue;">Hai my name is {{email}}</h1>
<a href="{{url_for('logout')}}">Logout</a>
</body>
</html>
In HTML elements we need to do a logic. So you need to use
{% %}
, to catch flash messages thrown from the backend, We can use the functionget_flashed_messages()
and can be defined in a variable to make it easier to use{% with messages = get_flashed_messages() %}
. The variable name is messages.Before the flash message appears, all you have to do is check if the backend is throwing a flash message
{% if messages %}
. Because of the possibility of more than one flash message, we can also looping the flash message. In the flask we can loop in the following way:{% for message in messages %}
and then we can print out that data with{{message}}
.Now we can do a test, whether our code is running properly. we can see an example like the picture below:
We can see in the picture above we have succeeded in generating a flash message, but the flash message still looks simple, we will do the styling in the next section
- Styling flash message
By default flash message doesn't have style. But we can style flash messages, I will combine the flash message with the styling of the device. for that we need to import CDN from bootstrap:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
profile.html
<!DOCTYPE html>
<html>
<head>
<title>Template Jinja2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<h1>This is the profile page</h1>
<h2 style="color:blue;">Hai my name is {{email}}</h1>
<a href="{{url_for('logout')}}">Logout</a>
</body>
</html>
- After importing bootstrap we can use the classes
{{message}}
</div>
- We can see the results as shown below:
We can see we have done to combine it with the bootstrap style.
- Flash message for logout
Now I will make a flash message during logout. the code is not much different from what we did when logging in, we only need to make a flash message in routing logout
app.py
@app.route('/logout')
def logout():
session.pop('email', None)
flash("You have successfully logged out", "warning")
return redirect(url_for("login"))
Because the route function above will redirect to the login page. then we will bring up the message in the login.html section.
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<h1>Form Login</h1>
<form action="/login" method="post">
<label for="">Email</label><br>
<input type="text" name="email" autocomplete="off"><br><br>
<label for="">Password</label><br>
<input type="password" name="password"><br>
<input type="submit" name="" value="login">
</form>
</body>
</html>
- If all steps have been completed, it can be run as shown below:
Can be seen in the picture above, the flash message goes well and we can do styling with any CSS framework that we use, not much different when styling HTML elements normally. so many of these tutorials can help you. thank you
Curriculum
Web developement with python #1 : Flask initialization and Routing system
Web development with python #2 : Templating jinja2 and Method POST on routing system
Web development with python #3 : Get method, Query parameter and Navigate Routing
Web development with python #4: Store cookie and Get cookie in template
Thank you for your contribution.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @mcfarhat! Keep up the good work!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!