In this tutorial, you will learn how to install flask and create a simple web app using flask.
Flask is a python web framework that you can use to create python web apps.
If you are a python programmer or just starting to learn python, and want to build web apps or websites written in python, flask is one of the best python web frameworks that you can use.
Step 1 - Create virtual environment
Before you install flask on your system, you need to create the virtual environment for the project that you will be working. Creating a virtual environment is necessary because when you install packages or libraries for one project they won't affect other projects.
First you need to create the project folder, you can name this folder anything you want. However, we'll be naming it flaskproject
mkdir flaskproject
Next, cd into the project folder that you created
cd flaskproject
Install virtual environment
pip install virtualenv
Now, you can create the virtual environment by running the command below
python3 -m venv .venv
After creating the virtual environment, you need to activate this environment, simply run the command below to do this
. .venv/bin/activate
Step 2 - Install Flask
Once you have created the folder for your project, and setup the virtual environment, you can now install flask. To install flask, run the command below
pip install flask
sudo apt install python-pip
After installing pip, try to install flask again.
Step 3 - Create flask web app
The app that we are going to create for this tutorial, is called flaskproject.py. So, first we need to create the python file.
Note: In the first step we created the folder flaskproject
this is the folder where we are going to create the python app.
We are using touch command to create this python file. However, you can use any text editor you want.
cd flaskproject
touch flaskproject.py
Next, you need to copy the code below into the flaskproject.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index_page():
return "<p>This is the index page</p>"
if __name__ == '__main__':
app.debug = True
app.run()
The code above will return <p>Hello, World</p>
. The code  works, but let's explain how this code works.
So the first thing that you need to do when coding a flask app is to import flask
from flask import Flask
After importing flask, you need to create a flask instance
app = Flask(__name__)
Next, you need to create routing. Routing allows you to run the code only on the route you specify. For example, let's say you want to execute your python code on index file, then to do this you will need to set your routing as below.
@app.route('/')
To set another routing, simply replace /
with your routing. Let's say you want to create an about function which routes you to /about
@app.route('/about')
After setting up routing, you need to create the function which will get executed on the given route. The index page function that we created looks like below
@app.route("/")
def index_page():
return "<p>This is the index page</p>"
Now, in the second step, we created the app object app = Flask(name)
to be able to run this code, you need to add the code below into your flask project, this part is very important because your code will not run without it.
if __name__ == '__main__':
app.debug = True
app.run()
app.debug to true
. Debugging is useful because if your code has bugs then you will be able to identify the cause and fix them. Do not use debugging in a production server.This is the complete code that we wrote.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index_page():
return "<p>This is the index page</p>"
@app.route("/about")
def about_page():
return "<p>This is the about page</p>"
if __name__ == '__main__':
app.debug = True
app.run()
So far the code is pretty basic, let's add some html files on it. Since we have two functions created, index and about, assuming these are pages in a website, let's add the html files for each function. So when you browse to /
or /about
, to get the html file displayed instead of just a text.
First thing that you need to do is to create the templates
folder, this folder should be created inside the project folder where your python code is. For example, in our case the main project folder is called flaskproject
inside flaskproject is flasproject.py
which contains the whole code for our app, and inside flaskproject
folder is also templates folder called templates
.
Now we are going to create two files, index.html
and about.html
inside the templates
folder, so the templates folder should look like this
index.html
contains
If you use visual studio code, you can generate the html below pretty quickly by pressing shift + 1 and click on !
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title of the flask app</title>
</head>
<body>
<div class="index-section">
<p>This is my index page</p>
</div>
</body>
</html>
And about.html contains
<div class="about-section">
<p>This is my about page</p>
</div>
Once you have created the two pages, you need to render them in your code. To do this, first you need to import render_template
module that will allow us to render a html file
On the first line where you imported flask, add the code below
from flask import Flask, render_template
Render index.html
@app.route("/")
def index_page():
return render_template('index.html')
Render about.html
@app.route("/about")
def about_page():
return render_template('about.html')
Now the code does exactly the same thing as before, but we are using html now instead of returning just text.
You may be asking, why is index.html different from about.html page, this is because index.html is the base file, in the index page we are going to add meta tags, scripts, css and other files, and extend it to the about page. This is necessary when creating a template in flask, because you want, let's say the design you are loading on the index.html to also apply on the about page, to do this we don't have to copy the index.html content into the about.html file because  that would create just repetitive code, and make it complicated for no reason.
For example, the title of the index page above is set to
<title>Title of the flask app</title>
This title won't change because it is not dynamic, to make it dynamic you need to use the correct syntax
<title>{{title}}</title>
Now, title will show anything we set it to show. For example, let's set the title of index.html to "Index Page Title"
@app.route("/")
def index_page():
index_title = "Index page Title"
return render_template('index.html', title=index_title)
And if you go to the index page, the new title will get displayed
However, to make it more easier to read and edit the code if you want to , you can set the title in the html files by using blocks.
<title>{% block title %} {% endblock %} Index Page Title</title>
The title "Index Page Title" is the static title, and it won't change. Assuming this is the name of the website, then we want this title to appear on every page. We don't have yet a title set for the about page, to set a title on the about page while the title on the index page stays the same, we are going to use the extends keywords.
Copy the code below and add it on about.html page
{% extends 'index.html' %}
{% block title %}About-{% endblock %}
{% block main %}
<div class="about-section">
<p>This is my about page</p>
</div>
{% endblock %}
Now we have both titles set up, so when you go on the about page, you will see both titles as shown in the image below
The {% block main %} {% endblock %}
on the about page will replace the {% block main %}{% endblock %}
on the index page . So when you are on the index page, you will see the content of the index page which is inside the blocks, and you will see the about content when you are on the about page.
main
you can call blocks anything you want. However, try to give them a descriptive name based on their function as this make it easy for you to edit them as needed.Let's now add some css to the index file. Create a folder called static inside the flask project folder, on the same path where templates is. In flask you cannot just link css files like you would do normally, css files have to go on a folder called static. Once you create the static folder, create the css file, we called this file main.css. However, you can call this file anything you want.
Next, you need to load the css file by using the url_for()
function
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
The code should look like this
Alternatively, you can add bootstrap or any other web framework that you want to build your project on. Â We chose bootstrap 5.3 for this project, to add bootstrap is easy all you have to do is to load the css and js files of bootstrap into your index file
Your index.html file should look like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title%}{% endblock %} Index Page Title</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
{% block main %}
<div class="index-section">
<p>This is my index page</p>
</div>
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
Now you can continue working on your projects and adding more content and more components, bootstrap has a lot of examples that you can use on your project without having to code them manually.
Start flask
To start the flask server, go to the folder where you created your project, and run the command below
python3 flaskproject.py
Replace flaskproject.py
with the name of your python file.
Output
This means the flask server was started successfully on port 5000, next go to 127.0.0.1:5000
using any browser and you should see your project running.
Conclusion
In this tutorial, we explained step by step how to create a web app with flask. We also explained how you can add a framework like bootstrap in your flask app.