23Jan 2020

A Tutorial on Building a Simple Web Application Using Python Flask

Flask is a web framework that has almost no dependency on external libraries. This is why it is classified as a microframework. It is one of the most popular Python web frameworks. The flask is based on Jinja2 and Werkzeug, both of these are the Pocoo projects. Jinja2 is a template engine and Werkzeug is a CGI library. In this tutorial, we will discuss how to use the flask to create a simple application.

So we will create a simple web application using flask. You should know python and HTML to proceed further. The application we are going to build will contain a home page. The home page will display a list of names and when clicked on any of them, a new page will open displaying their details. This is a beginner level tutorial, so we will try to keep it simple. But before we start writing code for this application, we will create a simple Hello World application in the flask to understand the basics.

from flask import Flask 
  
app = Flask(__name__) #creating a Flask class object   
 
@app.route('/')
def hello():  
    return "Hello World!";
	
if __name__ =='__main__':  
    app.run(debug = True)

Let’s understand the above code step by step. In the first line, the flask is imported from the Flask module. This is mandatory if we wish to use the flask. Now we have the flask imported, we need its instance. In the second line, we created a variable, named app, and it has an instance of the flask. In the very next line, we made the use of this instance for routing. Routing is an important part of any web application. Observe the following code.

@app.route('/')
def hello():  
    return "Hello World!";

The above code means, when the endpoint ‘/’ will be executed, the function hello() gets invoked. This is how routing is done in the flask. The string that is passed to the route() method defines the route of the function. The hello() function returns the message that will be displayed, i.e. “Hello World!”.

It is working. The idea behind this simple code was to make you understand the very basics of routing. We will be using routing in our application so you need to understand, how to create routes. So let’s begin by creating the homepage for our application.

We will create the homepage in HTML.

<html>
	<body>
		<div >
			<h1 style="text-align: center"> Welcome to the homepage! </h1>
			<hr>
		</div>
	</body>
</html>

This is a simple HTML code that displays “Welcome to the homepage!” on the screen. Earlier, we displayed a Hello World message in the browser. Now we have to display this HTML in the browser. Let’s create a route for it.

from flask import Flask 
  
app = Flask(__name__) #creating the Flask class object   


@app.route('/home') #defining route for homepage  


if __name__ =='__main__':  
    app.run(debug = True)

I added a route ‘/home’ in the above code. As of now, no function will be invoked when this route is executed. We have to create a function that will return the HTML code we wrote earlier for the homepage. Let’s create a function.

from flask import Flask
  
app = Flask(__name__) #creating the Flask class object   


@app.route('/home') #defining route for homepage  
def home():  


if __name__ =='__main__':  
    app.run(debug = True)

We have a function, named home(). Pay attention here. In the Hello World code, we simply returned “Hello World!”. But in this case, we have to return an HTML file. To do so, first, we have to create a new folder in the same place where the main file exists and name its templates. Then, we have to place the HTML file inside it. Not only this HTML file, but all the HTML files we will use in the application needs to placed in the templates folder. So I named the homepage file as “home.html” and placed it inside the templates folder. Now we can complete the home() function.

from flask import Flask, render_template  
  
app = Flask(__name__) #creating the Flask class object   


@app.route('/home') #route for homepage  
def home():  
    return render_template("home.html") 

if __name__ =='__main__':  
    app.run(debug = True)

First of all, observe the first line.

from flask import Flask, render_template

I imported render_template. This is required to render the HTML files. Now observe the home() function.

def home():  
    return render_template("home.html") 

Here, I used the render_template() function and passed the name of the HTML file to it. Remember, it is also necessary to mention the file extension.

Now the homepage is complete. Let’s run it and check what happens when we execute ‘localhost:5000/home’ in the browser.

Everything works perfectly till now. But we need more in our simple application. This homepage will display a few names and when clicked on any of them, a new page will open that will display their details. Let’s create a details page for James.

<html>
	<body>
		<div >
			<h1 style="text-align: center"> Welcome! James </h1>
			<hr>

			<h3>Name: <span>James</span></h3> 
			<h3>Age: <span>22</span></h3>
			<h3>Gender: <span>Male</span></h3>
			<h3>Location: <span>New York</span></h3>

		</div>
	</body>
</html>

I will name it james.html. This is a static and plain HTML that displays some detail about James. we have to place it inside the templates folder where the home.html exists. There are two steps ahead.

  • We have to create a route and function for james.html.
  • We have to add a link to the homepage that invokes the route.

Let’s create a route first.

@app.route('/james') #route for james's page

This is the route for James’s page. Let’s add a function that will render the james.html file. I will name the function as JamesDetails().

@app.route('/james') #route for james's page   
def JamesDetails():  
    return render_template("james.html")

We have the route and now we need a link that will invoke this route when clicked. Let’s upgrade the homepage.html file.

<html>
	<body>
		<div >
			<h1 style="text-align: center"> Welcome to the homepage! </h1>
			<hr>

			<ul>
				<li>
				<a href="{{ url_for('JamesDetails') }}">James</a>
				</li>
			</ul>
		</div>
	</body>
</html>

Here, I added an unordered list.

<ul>
	<li>
		<a href="{{ url_for('JamesDetails') }}">James</a>
	</li>
</ul>

Observe the <a> tag. In the value of the href attribute, I used the url_for() method. This method is used to link one page with another. To the url_for() method, we have to pass the exact name of the function that we are going to invoke. In this case, the function name is JamesDetails. This is the same function that renders the james.html file.

Everything is fine now. Let’s execute and check the homepage.

The link for James is appearing in the browser. Let’s click on James and see what happens.

Yes, james.html renders in the browser. Let’s add two more people to the homepage. Add the following code in the homepage.html file.

<li>
<a href="{{ url_for('LisaDetails') }}">Lisa</a>
</li>
<li>
<a href="{{ url_for('SamDetails') }}">Sam</a>
</li>

We have to create two more files – lisa.html and sam.html. Both of these files are similar to james.html, only the details are different. Let’s add routes for these HTML files.

@app.route('/lisa') #defining route for lisa's page  
def LisaDetails():  
    return render_template("lisa.html")

@app.route('/sam') #defining route for sam's page    
def SamDetails():  
    return render_template("sam.html")

This is how the main file looks now.

from flask import Flask, render_template  
  
app = Flask(__name__) #creating the Flask class object   

 
@app.route('/home') #route for homepage 
def home():  
    return render_template("home.html") 

@app.route('/james') #route for james's page  
def JamesDetails():  
    return render_template("james.html") 

@app.route('/lisa') #route for lisa's page  
def LisaDetails():  
    return render_template("lisa.html")

@app.route('/sam') #route for sam's page   
def SamDetails():  
    return render_template("sam.html") 


  
if __name__ =='__main__':  
    app.run(debug = True)

Remember two points –

  • HTML files should be present in the templates folder.
  • The string passed to the url_for method should be exactly the same as the function name.

This is how the homepage looks now.

That’s it! If you have any suggestions, let us know through the comment section.

Acodez is a renowned web design and web development company in India. We offer all kinds of web design and web development services to our clients using the latest technologies. We are also a leading digital marketing company providing SEO, SMM, SEM, Inbound marketing services, etc at affordable prices. For further information, please contact us.

Looking for a good team
for your next project?

Contact us and we'll give you a preliminary free consultation
on the web & mobile strategy that'd suit your needs best.

Contact Us Now!
Jamsheer K

Jamsheer K

Jamsheer K, is the Tech Lead at Acodez. With his rich and hands-on experience in various technologies, his writing normally comes from his research and experience in mobile & web application development niche.

Get a free quote!

Brief us your requirements & let's connect

Leave a Comment

Your email address will not be published. Required fields are marked *