Python is one of the most popular programming languages today. It is highly productive, user-friendly, and easy to understand, even for total beginners. That’s why I always recommend beginners to start with Python. Not just that, but building a web app with Python is pretty straightforward as well.
Python covers all essential topics a beginner requires to enter the development world. These topics include functions, object-oriented programming, and many others.
Read: The Ultimate Python Cheat Sheet – An Essential Reference for Python Developers
There are many areas in the development community where a beginner can enter after learning a programming language. One of them is web development. Everyone knows about web and websites, right?
If not then I highly recommend that you read the following article:
Web development is developing websites or developing for the web. You can be a front-end developer or back-end developer, or both. There are numerous technologies, such as front-end frameworks, backend services, middlewares, and a lot more.
Related: 12 Must-Have Skills of a Front End Developer
Python is also used in such technologies. It is popular among front-end developers, mainly because of its two popular frameworks – Django and Flask.
This tutorial is about building a web app with Python. For that, we are going to either use Flask or Django. But for this tutorial, we are going to focus on Flask.
But if you are going to be a Python developer, you should know the basic difference between Django and Flask.
Django is a full-stack web framework while Flask is a lightweight web framework. Django has everything in it. On the other hand, Flask does not provide everything you require to build an application. You may need third-party libraries and tools. So if you aim to build a simple application, go for Flask. You can say, Django is scuba diving while the Flask is snorkeling.
In this tutorial, we will discuss how to set up the environment for the Flask. Then we will create a simple Flask application step-by-step. After that, we will move further. We will learn how to render HTML pages and navigate to them from one page to another.
I will keep everything at a beginner level. So, don’t skip any part.
Also, if you are interested in a video version of building a web app with Python or Flask tutorial, then check out this course Flask Essential Training from LinkedIn Learning.
Setting up the Environment
Before we move ahead, let’s discuss how to set up the environment. I will be doing it on a Windows machine. If you are Linux or Mac user, then the procedures will be pretty much the same.
You need Python 3 installed on your system. Also, a basic knowledge of how to work with the command line is highly recommended.
Go to this link, https://www.python.org/downloads/ and download the latest version. While installing, you may see something like this during the process.
Make sure the two options are checked.
And then open your command prompt and create a folder for our project.
Enter the newly created folder and run the following command:
This creates and virtual environment.
You will see a new folder, named “venv” inside the project folder. Now, we need to activate the environment. Use the following command:
After activating, you will find yourself in the venv environment. Now we can install Flask. Type the following command:
PIP is the python package manager that comes with Python itself. Now we are ready for building a web app using Python Flask.
First Flask Application
The environment is set, Now we can create our first, simple Flask application. I am assuming you know how to code in Python, of course, and you have the basic knowledge of HTML and CSS.
So let’s start. In the same folder, create a new python file and name it, app.py.
Leave it empty for the time being. Then open the command line folder and type the following command: (Make sure you are on the same folder as the app.py)
set FLASK_APP = app.py
Open the app.py file. As of now, it is empty.
We will simply create an application that will display “Hello World!” in the browser. Let’s write the code step-by-step for better understanding.
The very first task is to import Flask on our file. So type the following statement inside your app.py file:
from flask import Flask
Next, we have to create an instance of Flask. Add the following to your app.py:
app = Flask(__name__)
Now, we have to create routes. To create a route, we use the route() method and pass the route name to it. Add the following:
@app.route('/')
The route here is ‘/’.
We can add anything after the slash, but as of now, leave it here. When this route will be executed, something should get invoked.
We will now create functions that get invoked when a route is executed. So on the same file, let’s create a function for our route:
def displayMessage():
return "Hello World!"
Your app.py should look like this until this point:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def displayMessage():
return "Hello World!"
The function displayMessage() will return “Hello World!”. This is it. Our first flask application is ready. Go back to the command line and type the following command:
Flask run
The application will run on port 5000.
Open a browser and go to the following address:
http://127.0.0.1:5000/
Congratulations on successfully building a web app with Python Flask. I know this may not be the application that you like to build. It is very very simple. But let’s just start here for now.
Using Routes and Rendering Templates
Hopefully, everything is clear on what is happening with our simple application. Let’s move further.
We will create a few HTML pages. Each page will have a different route. A specific HTML page will open when the route associated with it will be executed. We will start with the home page.
The route will be ‘/home‘. This time, the function will not return any string, instead, it will render an HTML page. I have updated the earlier code. Observe it once and then I will explain all the changes one by one.
I have updated the earlier code. Observe it once and then I will explain all the changes one by one.
from flask import Flask, render_template #1
app = Flask(__name__)
@app.route('/home') #2
def home(): #3
return render_template("home.html") #4
I have added some comments to the code. Each line with a pound sign denotes what is happening on that particular line. Let’s go ahead and discuss what is happening.
#1
The first change is in the first line. Along with Flask, I have imported another module, render_template. This will help us to render HTML pages in the browser.
#2
The second change is in the line where the route is defined. I changed the route name to ‘/home‘.
#3
Next, I changed the name of the function to “home“.
#4
This is the most important change. Earlier, we just returned a string from the function but this time, we are returning the render_template() method we imported earlier. Check the line again.
The argument passed to the render_template() method is the name of the file that will be rendered when this route is executed. Here, the name of the file is home.html.
Do you understand what is happening in this code? We created a new route and rendered an HTML page using render_template(). This won’t work right now because we do not have the home.html file.
If we are using HTML files, we need to create a new folder in the same place where our Python file is present. The name of the folder should be “templates“, nothing else.
Create a new HTML file with the below content and save it inside the templates folder.
<html>
<head>
<title>Home page </title>
</head>
<body>
<div >
<h1 style="text-align: center">
Welcome to the home page!
</h1>
</div>
</body>
</html>
This HTML file contains a simple HTML code that displays “Welcome to the home page!” with some CSS.
If your current application is still running then kill the running application by pressing control + C on your command line. Run your application again using the following command:
Flask run
Open the browser and navigate to “http://127.0.0.1:5000/home“. You will see something like this:
You can try the route we used earlier, i.e. “http://127.0.0.1:5000/“. It will just display error on the screen because no such route exist at the moment.
We can have as many routes as we want. Let’s create two more routes “/about” and “/contact“. Both of these routes will have different HTML pages, about.html, and contact.html.
We have to update the script. We will be adding two functions in order to route our application to the new pages that we are going to create. So, add the following to your app.py:
@app.route('/about')
def home():
return render_template("about.html")
@app.route('/contact')
def home():
return render_template("contact.html")
At this point your script should look like this:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/home')
def home():
return render_template("home.html")
@app.route('/about')
def home():
return render_template("about.html")
@app.route('/contact')
def home():
return render_template("contact.html")
Let’s go ahead and create our new HTML files. Make sure to put these new html files under the folder ‘templates‘.
First the about.html file:
<html>
<head>
<title>About </title>
</head>
<body>
<div >
<h1 style="text-align: center"> About </h1>
</div>
</body>
</html>
And then contact.html:
<html>
<head>
<title>Contact </title>
</head>
<body>
<div >
<h1 style="text-align: center"> Contact </h1>
</div>
</body>
</html>
Remember, these two files should be in the templates folder or else you will get an error.
Let’s try “http://127.0.0.1:5000/contact” on your browser.
It is working, but we don’t have to type the route in the address bar every time, right?
How about we have some links on the homepage that will help us navigate to the other pages?
Let’s discuss how we can achieve this functionality using Flask.
Navigating to Other Pages
Let’s make a few changes to our home.html:
<html>
<head>
<title>Home page </title>
</head>
<body>
<div >
<h1 style="text-align: center">
Welcome to the homepage!
</h1>
<ul>
<li>
<a>Contact</a>
</li>
<li>
<a>About</a>
</li>
</ul>
</div>
</body>
</html>
Make sure your Flask application is running. And then go to ‘http://127.0.0.1:5000/home‘
Now, you have two links on the home page. One for the Contact page and another for the about page.
As of now, nothing happens when these links are clicked. We will add the functionality next.
There is a method called url_for(). We have to imbed this method inside our home.html file.
We will add this method inside the href attribute of <a> tag.
This method will decide which page will be rendered when the link is clicked. Observe the following line:
<a href="{{ url_for('contact') }}">Contact</a>
We have to pass a string to the url_for() method and this string should contain the name of the function that was associated with the route.
Scroll up to check the name of the function below the contact route.
It should be “contact”. Let’s do the same for the about link.
The same should also work in case of our about.html file:
<a href="{{ url_for('about') }}">About</a>
Here’s the complete home.html file for you to see how everything is coming together.
<html>
<head>
<title>Home page </title>
</head>
<body>
<div >
<h1 style="text-align: center">
Welcome to the homepage!
</h1>
<ul>
<li>
<a href="{{ url_for('contact') }}">Contact</a>
</li>
<li>
<a href="{{ url_for('about') }}">About</a>
</li>
</ul>
</div>
</body>
</html>
Now, when the Contact or About is clicked, their respective pages will render.
Conclusion
Flask is simple and easy to understand.
In this tutorial, we covered a lot. Although we worked on building a web app with Python Flask that is very basic. But the goal is to understand the basic structure and concept behind our application.
We set up an environment then we created a simple application that displayed a message on the screen. Pretty simple, right?
The aim here was to get you familiar with the syntax used in the Flask, especially for routes.
We created multiple routes later and also rendered HTML pages.
It is important that you know how to render pages in Flask.
Then we move further, made changes to our home page so we can navigate to other pages directly from there.
I kept everything simple, on a beginner level.
Flask is lightweight, thus easier to understand. Try to create multiple HTML pages.
You can also try to navigate back to the home page from contact or about page. Give it a try. If you know more about HTML and CSS, try to add images and make them navigable. Use buttons or other cool stuff. The more you practice, the more you will learn.
Make sure to check out the following courses on Flask from LinkedIn Learning:
Remember that you can try out these courses for free. So, sign up today to learn more about building a web app with Python & Flask.
What do you prefer? Django or Flask for building a web app with Python? And why?