In this chapter, we will look at some of the important concepts of flask. I am assuming that you know what flask is all about and what you can do with flask. If not then visit Flask
I am also assuming that you have a solid understanding of python programming language. If not just google python tutorial and you will see a lot of tutorials. But Python docs is the best way to learn python.
In this chapter, we will be creating a lot of scripts or python files which we will run from the command prompt.
To create a script you can open your favourite text editor and then type the python code, save it with a file extension
Then command prompt will run the script and gives the expected output.
In this chapter, as there is a lot of content to cover, I am using IPython notebook. Assume that each and every input is a script file. Create one and fire up the command prompt or terminal, you will get a message stating that the server is running at
If in any case you are not able to use your command prompt, then open the script in IDLE editor and then run the code by hitting F5 or Run > Run Module.
More information from here: Python central
A video:
You may also find the following video helpful if you are facing any problem.
I am also assuming that you have a solid understanding of python programming language. If not just google python tutorial and you will see a lot of tutorials. But Python docs is the best way to learn python.
In this chapter, we will be creating a lot of scripts or python files which we will run from the command prompt.
To create a script you can open your favourite text editor and then type the python code, save it with a file extension
.py
. Now open the command prompt in the folder you have saved python and then type python your_file_name.py
Then command prompt will run the script and gives the expected output.
In this chapter, as there is a lot of content to cover, I am using IPython notebook. Assume that each and every input is a script file. Create one and fire up the command prompt or terminal, you will get a message stating that the server is running at
http://localhost:5000
.If in any case you are not able to use your command prompt, then open the script in IDLE editor and then run the code by hitting F5 or Run > Run Module.
More information from here: Python central
A video:
You may also find the following video helpful if you are facing any problem.
A hello world application¶
We will start with a simple and easy hello world application, which will show Hello world in the web browser.
In [ ]:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello_world():
return "Hello world"
if __name__ == "__main__":
app.run()
Save the above file as app.py somewhere on your local computer. Open the command prompt in that location and type
Now that we are sure that it is running, we will try to make sense of the code that we have written.
Adding HTML in
We can even add HTML tags in our return statement and the browser will render the tags. Lets make a simple web page.
python app.py
, you will get "* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
". Open http://127.0.0.1:500/hello or http://localhost:5000/hello and you should see something like this
Now that we are sure that it is running, we will try to make sense of the code that we have written.
- We have imported
Flask
class fromflask
module. - We have created an instance (
app
) of the class so that we can use it in our code. - For URL's we are using the
route
decorator, so that when you type127.0.0.1/hello
in the web browser then the functionhello_world
is called which will obviously returnHello world
. - This
if
statement is checking if the source file name is same as the one which we are executing and the app is started. Further Reading: What doesif __name__ == “__main__”:
do?
Adding HTML in return
statement¶
We can even add HTML tags in our return statement and the browser will render the tags. Lets make a simple web page.
In [ ]:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello_world():
html = """
<h1>Anivarth Peesapati</h1>
<p>Hello there,<br />
I am Anivarth Peesapati. I love {}
</p>
""".format("Python")
return html
if __name__ == "__main__":
app.run()
After the app is running, you should see something like this:
Just with the help of the above example we can explain many things.
- We can return variable values also.
- HTML can also be added to the return strings.
- To embed some variables in the strings we can use
[format](https://docs.python.org/2/library/stdtypes.html#str.format)
function.
Dynamic URL's¶
If you have ever noticed, facebook has URL's like http://facebook.com/anivarth. Depending on your name the URL will change. And depending on the URL the output of the web page will change. In flask we can create similar variable URL's also called as Variable rules. We will see an example to understand it better.
In [ ]:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/<name>')
def hello_world(name):
return "<h1>{}</h1>".format(name)
if __name__ == "__main__":
app.run()
As you can see, the way we define the URL also has changed. It is compulsory that we will give this variable as input to the function(
Sometimes, it is necessary to restrict the user to enter only numbers in the variable URL. Then you can add
hello_world(name)
) that we are defining. Otherwise, you will see an error. Restart the app(Restarting the terminal always is boring there is a solution for it and we will see it later) and go to http://127.0.0.1/Anivarth and you should see something like this:
If you change my name to your name, you should see your name in the browser. But the h1
tags are not replaced in any case. Facebook works in a similar way. They have created all the basic HTML and only the content(Your name, friends etc.) varies according to the URL.Sometimes, it is necessary to restrict the user to enter only numbers in the variable URL. Then you can add
int:
in front of the variable name. Lets see an example.
In [ ]:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/<int:ph_no>')
def phone_number(ph_no):
return "Your phone number is {}".format(ph_no)
if __name__ == "__main__":
app.run()
Restart the app and when you visit http://localhost:5000/12345, you will see something like this:
In a similar way you can constrain the variable. You can use the following depending on your requirement.
In a similar way you can constrain the variable. You can use the following depending on your requirement.
Constraint | Remarks |
---|---|
string | accepts any text without a slash (the default) |
int | accepts integers |
float | like int but for floating point values |
path | like the default but also accepts slashes |
any | matches one of the items provided |
uuid | accepts UUID strings |
Debug Mode¶
If you have observed, till now we have been restarting the server everytime there was a change in the script. But this is not really necessary. Flask can sense the changes in the script and will automatically reload the script for you. You can do that usingapp.run(debug=True)
at the end. You can see the usage in the next example.HTTP methods¶
When you open a web page using a URL, python will serve the webpage using a method called asGET
. But this is not always the same case. Most of the times when you submit a form, the browser will POST
the data and based on the data, the server will respond with the GET
method. If you have observed your command prompt or terminal, after you have opened a page, you should see some GET
methods.You can read more about HTTP requests from here: HTTP/1.1: Method Definitions, HTTP, HTTP requests Methods
We can also use POST method in flask. Lets implement a simple form to create a POST request on flask.
In [ ]:
# app.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/form', methods = ['GET', 'POST'])
def form():
if request.method == 'POST':
return request.form['flask']
else:
return "<form method='POST'><input type='text' name='flask'/>\
<input type='submit' value='submit' /></form>"
if __name__ == "__main__":
app.run(debug=True)
If you run the file above, then you should see a page something like this:
Before we proceed further we will understand the above program. In the decorator we have added
Else, we will just show the user a form in which he/she can enter the value. In the
In the run command we have also added
Before we proceed further we will understand the above program. In the decorator we have added
methods = ['GET', 'POST']
. This means that we are telling python to accept both GET, POST
methods from the browser. In the function, we are checking if the methods are POST
and if it is POST
method, then we will return the value(request.form['flask']
, where flask
is the name of the input tag.) that has been entered in the form.Else, we will just show the user a form in which he/she can enter the value. In the
else
statement we have added the HTML code which I am assuming that you are already familiar with it.In the run command we have also added
debug = True
which means that, from the next time you make changes to the script they are automatically loaded.Templates¶
Till now we only had few HTML tags in our website pages. But what if you have a very big HTML file? Of course you can add that to thereturn
command, but don't you think that it will make the code look messy? Yes, it will. For this reason we can use templates in Flask. We will see the code first and then make sense of it.
In [2]:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/test-template')
def testing_template():
return render_template('test.html')
if __name__ == "__main__":
app.run(debug = True)
Before we save the above file, we will have to create 'test.html' file. To do that create a new folder with name templates in the folder where the
After you have saved the HTML file, go ahead and save changes to the
If there are no errors then go ahead an open http://127.0.0.1:5000/test-template and you should see something similar to this:
The only changes that we made are, we have added
The app.py file is as follows:
app.py
file resides. to make it simple, your folder structure will look as follows:├── app.py └── templates ├── test.htmlWe will start with something very simple. Save the test.html file with the following code in it.
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> </head> <body> <h1>Radius of Circle</h1> </body></html>
app.py
. If you editing the code in the old app.py file, then flask will automatically reload the changes for you. Otherwise you should start the server.If there are no errors then go ahead an open http://127.0.0.1:5000/test-template and you should see something similar to this:
The only changes that we made are, we have added
render_template
function with the HTML file name and it took care of everything else for us.Using Variables in templates¶
I don't think that the templates are really useful if they just serve the same file everytime. There should be a change to the file either based on the url or based on input or based on time and so on. To do this we can use python variables in templates. We will see an example.The app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/test')
def test():
return render_template('test.html', name = "<h1>Anivarth Peesapati</h1>")
if __name__ == "__main__":
app.run(debug = True)
Now the HTML file will be as follows:
Remember to save the file in the templates folder. I am saving the file as test.html. But if you save the file with a different name, then make sure that you will also update the file name in the python script.
If you run the file you will see something like this:
In HTML files, we will refer to the variables using
But there is a problem! If you have observed, the value that we have given to the
For example if you will give
Now to overcome this problem, we will have to append
Let's modify the HTML file and the python script will remain the same.
After the changes the output in the browser will be as follows:
As we have got familiar with the python variabls, we will do something a little bit complex. We will print the calendar for a year based on the URL of the user.
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> </head> <body> {{ name }} </body></html>
If you run the file you will see something like this:
In HTML files, we will refer to the variables using
{{ variable_name }}
syntax. When we are rendering the template, we will refer to variable_name
to assign a value. In our example as you can see, we are using the name
variable which we have used in the HTML file and using the same variable we have assigned a value in the python script.But there is a problem! If you have observed, the value that we have given to the
name
variable is <h1>Anivarth Peesapati</h1>
, and we are expecting python to render the template with a heading. But this didn't happen, becase jinja by default will assume that the value that we are giving as input are not safe and will escape the characters.For example if you will give
<
as input it will convert it to <
. You can read more about escaping from here: Using character escaping in HTML and the HTML escape charactersNow to overcome this problem, we will have to append
|safe
to the variable name - Like {{ variable_name|safe }}
. This will not do the character escaping for you. You can read more about the Character escaping in Jinja from here: Controlling EscapingLet's modify the HTML file and the python script will remain the same.
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> </head> <body> {{ name|safe }} </body> </html>
As we have got familiar with the python variabls, we will do something a little bit complex. We will print the calendar for a year based on the URL of the user.
In [ ]:
# app.py
from flask import Flask, render_template
from calendar import HTMLCalendar
app = Flask(__name__)
@app.route('/<int:year>')
def calendar(year):
html_calendar = HTMLCalendar()
year_calendar = html_calendar.formatyear(year)
return render_template('test.html', calendar = year_calendar, year = year)
if __name__ == "__main__":
app.run(debug = True)
We are using Variable URL and python
If your server is running go to http://localhost:5000/2017 and then you will see something like this:
. If you change the number in the URL you will see the calendar for that year. It should be noted that the maximum number that you can enter is 9999.
More about Jinja Templating from here: Jinja2
[Calendar](https://docs.python.org/2/library/calendar.html#calendar.HTMLCalendar)
module to generate HTML calendar for us. Now the HTML file will be as follows:
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> </head> <body> <center><h1>Calendar for the Year {{ year }}</h1></center> <center>{{ calendar|safe }}</center> </body> </html>
. If you change the number in the URL you will see the calendar for that year. It should be noted that the maximum number that you can enter is 9999.
More about Jinja Templating from here: Jinja2
Building URL's¶
Till now we have created many webpages. But what if, we had to link from one page to another? To solve this problem we will use theurl_for
function. We will see a small example for that:
In [ ]:
# app.py
from flask import Flask, render_template, url_for
from calendar import HTMLCalendar
app = Flask(__name__)
@app.route('/index')
def index():
return "This is an index page"
@app.route('/flask/<int:number>')
def flask(number):
return "This is flask page - {}".format(number)
@app.route('/links')
def urls():
return "<a href='{}'>Index</a><br /><a href='{}'>Flask</a>".format(url_for('index'), url_for('flask', number = 10))
if __name__ == "__main__":
app.run(debug = True)
If you run the script and open http://127.0.0.1/links then you will see something like this:
As you can see we have used
Now in the static folder create a file and name it style.css. At the end of this operation your folder structure will look as follows:
Now the code in the style.css will be as follows:
Don't forget to save the file in the static folder.
Now test.html file will contain the following code:
Note that you should save the file in the templates folder. There are two things to note from this HTML page:
Now open the browser and type the year for which you want the calendar. I want to see the calendar for 2017 and so I will type: http://localhost:5000/2017 . You should see something similar to this:
Remember that you should store all the static files in the static directory only. Of course you can make subfolders in the static directory.
app.py will have the following code:
As you can see we have used
url_for
function and flask will build the links for you. url_for
will take the name of the function which you are referencing. If the URL has variable rules, then you will add the value after the name of the function. This function is also available in the jinja templates also. url_for function can also do more things. If you want to know more, then you can see: url_for API.format
function that we have used can be seen here: str.formatstatic files¶
In the calendar example we have seen, eventhough we were able to show the calendar it was not looking great. I mean it was missing styling information. There are many options for us to add the style information.- External Style sheet
- Internal Syle Sheet
- Inline Style
url_for
function to use the static files. But before we do that first create a folder with name static in the folder where app.py file resides.Now in the static folder create a file and name it style.css. At the end of this operation your folder structure will look as follows:
├── app.py ├── static │ ├── style.css └── templates ├── test.html
Now the code in the style.css will be as follows:
table, td, tr, th{ font-family: 'Lora', serif; border: 1px solid red; padding: 5px; }
Don't forget to save the file in the static folder.
Now test.html file will contain the following code:
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" /> </head> <body> <center><h1>Calendar for the Year {{ year }}</h1></center> <center>{{ calendar|safe }}</center> </body> </html>
Note that you should save the file in the templates folder. There are two things to note from this HTML page:
url_for
function has been used for getting the static files- I have also added a link to google fonts to get the font family.
Now open the browser and type the year for which you want the calendar. I want to see the calendar for 2017 and so I will type: http://localhost:5000/2017 . You should see something similar to this:
Remember that you should store all the static files in the static directory only. Of course you can make subfolders in the static directory.
for loop in templates¶
We can use for loop in jinja templates. Lets see an example:app.py will have the following code:
In [ ]:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def looping():
return render_template('test.html', loop = xrange(10))
if __name__ == "__main__":
app.run(debug = True)
test.html file will have the following code(I am not following any Web standards, you can add them if you want).
Now run the server and you should see something similar to this:
I am assuming that you are able to understand the code directly because it is mostly similar to python code and direct. It should be noted that, there is no need for indentation in the HTML code.
test.html is as follows:
There is no change in the app.py file. Run the server and you should see something similar to the following:
You can do more things with Jinja Templates. For more details visit: Synopsis, List of Control Structures
For example we will continue with the calendar app that we were creating.
Now the app.py file is as follows:
{% for i in loop %} We are looping {{ i }}<br /> {% endfor %}
I am assuming that you are able to understand the code directly because it is mostly similar to python code and direct. It should be noted that, there is no need for indentation in the HTML code.
if-else-elif in templates¶
We have for loop to loop through the templates, but we also need someif
conditions to make decisions. Yes, Jinja(templates) also have if
statements. We will print the multiples of 3, 5 below 10 on the webpage.test.html is as follows:
{% for i in loop %} {% if i%3 == 0 %} {{ i }} is a multiple of 3<br /> {% elif i%5 == 0%} {{ i }} is a multiple of 5<br /> {% else %} {{ i }} is neither a multiple of 3 not 5 <br /> {% endif %} {% endfor %}
There is no change in the app.py file. Run the server and you should see something similar to the following:
You can do more things with Jinja Templates. For more details visit: Synopsis, List of Control Structures
Request data¶
Few sections ago, in the HTTP methods section, we have seen a little bit about the POST method. But in this section we will see more of this in detail.For example we will continue with the calendar app that we were creating.
Now the app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, render_template, url_for, request
from calendar import HTMLCalendar
app = Flask(__name__)
@app.route('/', methods = ['GET', 'POST'])
def calendar():
if request.method == "POST":
year = int(request.form['year'])
year_html = HTMLCalendar().formatyear(year)
return render_template('test.html', calendar = year_html, year = year)
else:
return """
<form method = "POST">
<input type="test" name = "year" /><br />
<input type = "submit" value = "Submit" />
</form>"""
if __name__ == "__main__":
app.run(debug = True)
In the code, we are telling python that the present webpage can have both
test.html file is as follows(I am assuming that you already have style.css):
If you run the server, then you will see something similar to these:
You can see more about the form data from here: Accessing Request Data, File Uploads
POST, GET
methods(methods = ['GET', 'POST']
). The if
statement checks if the method is POST. If the method is POST, then the html of the calendar is returned. Else the form is returned. So that if the user submits the form the value is sent as POST and the calendar for the year is shown.test.html file is as follows(I am assuming that you already have style.css):
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" /> </head> <body> <center><h1>Calendar for the Year {{ year }}</h1></center> <center>{{ calendar|safe }}</center> </body> </html>
If you run the server, then you will see something similar to these:
You can see more about the form data from here: Accessing Request Data, File Uploads
Cookies¶
Cookies are small files which are stored on a user's computer. They are designed to hold a modest amount of data specific to a particular client and website, and can be accessed either by the web server or the client computer.We can also create and store cookies in a client browser. Let's see an example. app.py as follows:
In [ ]:
# app.py
from flask import Flask, render_template, make_response
app = Flask(__name__)
@app.route('/cookie')
def cookie():
response = make_response(render_template("test.html"))
response.set_cookie('website', 'Radius of Circle')
response.set_cookie('author', 'Anivarth Peesapati')
return response
if __name__ == "__main__":
app.run(debug = True)
Here in the
You can create a new HTML file or change the test.html file with the following code:
Run the server and you will just see a "The page has a cookie". Now to check if the cookie has been set, we can do as follows:
If you can help me with the browser in your OS, then you are welcome.
app.py is as follows:
cookie
function we are storing two cookies. You can store any number of cookies.You can create a new HTML file or change the test.html file with the following code:
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" /> </head> <body> <p>This page has a cookie</p> </body> </html>
If you can help me with the browser in your OS, then you are welcome.
Access the cookie¶
To access the cookie, we can use therequest.cookies
attribute. app.py is as follows:
In [ ]:
from flask import Flask, render_template, make_response, request
app = Flask(__name__)
@app.route('/cookie')
def cookie():
response = make_response(render_template("test.html"))
response.set_cookie('website', 'Radius of Circle')
response.set_cookie('author', 'Anivarth Peesapati')
return response
@app.route('/')
def index():
website = request.cookies.get('website')
return render_template('test.html', website = website)
if __name__ == "__main__":
app.run(debug = True)
In the above file, we have also added an
The update
Now run the file and visit http://localhost:5000 . You will see a text stating "Website is Radius of Circle". If you don't believe me, open a Private browsing window or Incognito tag and visit the same URL, you will see something else.
index
function which we will take read the cookies and the data is sent to the HTML file as a variable. Rest of the code is same.The update
test.html
is as follows:
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" /> </head> <body> {% if website %} Website is {{ website }} {% else %} <p>This page has a cookie</p> {% endif %} </body> </html>
Redirect¶
I think that everyone is aware of what redirect is and we will directly see an example for that. app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
return "This is an index page"
@app.route('/redirect')
def redirect_this_page():
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
redirect
takes the url of the page to which it has to redirect. To make our work simple I have used url_for
function. Rest of the thing is simple.Now run the file and visit http://localhost:5000/redirect and it will automatically redirect you to index page.
handling errors¶
Sometimes when we browse a website, we will see a 404 Not found error. This is because there is no page for such URL. For example on google you will see a page like this:In flask when you open an Unknown URL then you will see something like this: But you can add some style sheets or add custom template to this kind of pages. For this we will use something called as error handlers. Lets see an example.
In [ ]:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "This is an index page"
@app.errorhandler(404)
def error_404(error):
return "<h1>Hello users, sorry there is no page with this url!</h1>"
if __name__ == "__main__":
app.run(debug = True)
When you visit some url other than the index page you will see something similar to this:
Remember that the function will take some
Our app.py file is as follows:
Remember that the function will take some
variable_name
as input and it can be further used as variable in the function. You can also create custom pages for 500, 400 etc. If you want to know the status codes, then you can see from here: List of HTTP Status Codeabort¶
Sometimes, you deliberately will be in need of aborting a function with error pages. Then you can use this function. For example, if the user has entered a wrong data in the text input and you want to terminate the program execution, then you can show the user 500 error instead of the error that happened in your program.Our app.py file is as follows:
In [ ]:
# app.py
from flask import Flask, abort
app = Flask(__name__)
@app.route('/')
def index():
return "This is an index page"
@app.errorhandler(404)
def error_404(e):
return "<h1>Hello users, sorry there is no page with this url!</h1>"
@app.route('/error')
def create_error():
# this page will show 404 error
abort(404)
if __name__ == "__main__":
app.run(debug = True)
Run the server and visit the error page and you will see the custom 404 error page.
sessions¶
Even though you can use cookies for storing the user login data, they are not really secure. For this reason flask has sessions. These are far better and very much secure when compared to simple cookies. You can create cookies in the following way:
In [ ]:
# app.py
from flask import Flask, session, url_for
app = Flask(__name__)
app.secret_key = "some secret key you want"
@app.route('/')
def index():
if 'name' in session:
return "Welcome back {}. To logout <a href\
='{}'>Click Here</a>".format(session['name'], url_for('logout'))
return "Welcome guest.\
To login <a href='{}'>Click here</a>".format(url_for('login'))
@app.route('/login')
def login():
session['name'] = "Anivarth"
return "You are now logged in. To logout \
<a href='{}'>Click here</a>".format(url_for('logout'))
@app.route('/logout')
def logout():
session.pop('name')
return "Logged out!"
if __name__ == "__main__":
app.run(debug = True)
We have to create a secret key for the session to work. Value of secret key can be anything. It is recommended that the value is something random.
Now in the code, when the user visits the index page - if a session exists, then the user is welcomed with their name, else, they are asked to login by visiting the login page.
In the login page we will create a session object which will save name of the user.
In the logout page we will remove the name of the user from the session and will notify the user with Logged out! message.
Of course, login and logout will not be as primitive as this one. This is the core concept. You can add forms and many other things to make it more secure.
Now run the server and you will see something like this:
You can read more about sessions from here: Flask Sessions
In a similar way you can flash the messages to the user without changing the data in the return function. You can do that as follows: app.py
Now in the code, when the user visits the index page - if a session exists, then the user is welcomed with their name, else, they are asked to login by visiting the login page.
In the login page we will create a session object which will save name of the user.
In the logout page we will remove the name of the user from the session and will notify the user with Logged out! message.
Of course, login and logout will not be as primitive as this one. This is the core concept. You can add forms and many other things to make it more secure.
Now run the server and you will see something like this:
You can read more about sessions from here: Flask Sessions
flashes¶
If you have ever entered a wrong username and password on a webpage, then you should have got a message stating, you have entered a wrong username or password. In a similar way when you have added a product to the cart there will be a message stating that the product has been added to the cart. These are some of the endless examples.In a similar way you can flash the messages to the user without changing the data in the return function. You can do that as follows: app.py
In [ ]:
# app.py
from flask import Flask, flash, render_template
app = Flask(__name__)
app.secret_key = "dasdf"
@app.route('/')
def flash_message():
flash('This is a flash message')
return render_template('test.html')
if __name__ == "__main__":
app.run(debug = True)
The only thing that is unfamiliar to you is the flash function, which will flash the message in the user's browser. If you use bootstrap, then usually you will show flashes using Alerts
Now the test.html file will be as follows:
Run the server and you will see the message flashed.
This tutorial is not yet complete. If you are comfortable with using flask from now, then you should first read Quickstart before you proceed further.
As always if you have any doubt or didn't understand anything then comment in the comment box and I will be happy to help you.
If you have any suggestions or feedback or if you have found any typo in this post, Please do comment in the comment box and I will be very happy to see your message.
You can also contact me.
Thank you. Have a nice day😃.
Now the test.html file will be as follows:
<!doctype html> <html lang='en'> <head> <title>Radius of Circle</title> <link href="https://fonts.googleapis.com/css?family=Lora"" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}" /> </head> <body> {% with flashes = get_flashed_messages() %} {% if flashes %} <ul> {% for message in flashes %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <p>This page features flashes.</p> </body> </html>
This tutorial is not yet complete. If you are comfortable with using flask from now, then you should first read Quickstart before you proceed further.
As always if you have any doubt or didn't understand anything then comment in the comment box and I will be happy to help you.
If you have any suggestions or feedback or if you have found any typo in this post, Please do comment in the comment box and I will be very happy to see your message.
You can also contact me.
Thank you. Have a nice day😃.