Setting up a flask app

NM
JK
newton mbugua
Co-authorJohn Kamau
Mar 30, 20245 min read

Flask Image

What is Flask?

Most programmers would agree that Python is one of the easiest languages. For me, it is a lot like English with a lot of logic and spacing 😊. One of the best things about Python is its ability to be modified for different purposes, one being web development, in the form of web frameworks. There are many Python frameworks but those that stand out include;

  • Django
  • Flask
  • FastAPI

In this article, we shall take a peek at Flask Web Framework.

So, what if flask? From the description above we know that Flask is a Python web framework. But what is it?

Well to understand this let’s understand what a framework is. A framework in programming simply means a tool that provides you with some sort of functionality and utilities out of the box. For example, Django will provide you with a lot of functionality such as routing, authentication, an admin portal, connection to a database and more, out of the box without the need for you to make your implementation.

This is great, I mean it makes my work easy to focus on the main part of development. But sometimes you might not need all that functionality or you want something simple with your implementation.

Here is where Flask comes in. Flask is a minimal Python micro-framework based around Werkzeug and Jinja that gives you essential functionality and allows you to add your own with other Python packages.

Python Frameworks

How does it work?

It was developed by Armin Ronacher, who led a team of international Python enthusiasts called Poocco. Flask's foundation is based on the Werkzeug WSGI toolkit and Jinja2 templating.

WSGI

Stands for Web Server Gateway Interface. This is a standard used in Python that specifies how web servers communicate with web applications.

Werkzeug

Werkzeug is a WSGI toolkit that implements requests, response objects, and utility functions.

Jinja2

A popular Python template engine. It allows the combination of a web template with a data source (backend) to render dynamic data. This is what enables Python syntax on an HTML file.

index.html
1<ul>
2    {% for item in items %}
3    <li>{item}</li>
4    {% endfor %}
5</ul>


How to setup a simple flask app

Now that we understand how a flask app works and what technologies it utilizes how do we set it up? That is also fairly simple. The only requirement is that you have Python and pip package installer.

We can have a flask app on one file. This is not recommended for a production application but since we are learning ...

terminal
1pip install flask

😲 Just like that you can use Flask on your machine.

Let's set a small flask app that returns "hello world" when you access a local URL for example http://localhost:5000

app.py
1# import flask
2from flask import Flask
3
4# create a Flask instance
5app = Flask(__name__)
6
7# create our initial route
8@app.route('/') # In flask this is a decorator
9def index():
10    # function that returns Hello world
11    return "Hello world"
12
13# run our flask application instance
14if(__name__)=='__main__':
15    app.run(debug=True)

Open your favourite code editor, and in any location of choice create a folder and give it a name. Inside the folder create a file app.py and write the above code.

In your terminal/cmd / powershell, go to the location of the folder and run the following command.

terminal
1python app.py

Now when you visit http://localhost:5000 you will see "Hello world"

In a real-world project, you would be returning a template instead of Hello World. You know what let’s do that.

create another folder next to app.py called templates and add an index.html file Structure will now be;

folder.txt
1project
2|__ templates
3    | index.html
4|__ app.py

In our index.html file let’s add some boiler html code.

index.html
1<!DOCTYPE html>
2<html lang="en">
3    <head>
4        <title>Our Flask app</title>
5        <style>
6            .container {
7                margin: 2rem;
8                background-color: wheat;
9                padding: 20px;
10                border-radius: 10px;
11                height: 20vh;
12                width: 50%;
13            }
14            .container h2 {
15                text-align: center;
16            }
17        </style>
18    </head>
19    <body>
20        <div class="container">
21            <h2>Hello Flask app</h2>
22        </div>
23    </body>
24</html>

Now let's modify our Flask application to render out the template.

app.py
1# add some imports from flask
2from flask import Flask, render_template
3app=Flask(__name__)
4@app.route('/')
5def index():
6    # now we return our index.html file
7    return render_template('index.html')
8if(__name__)=='__main__':
9    app.run(debug=True)

What happens is that Flask will look for a template with the name index.html in the templates folder and return the template to the browser. The browser will render the html page with the content in the file.

What if we want to pass data to our template

Very easy as well, let's do it by example let's modify our flask app to return a list of animal names.

app.py
1# add some imports from Flask
2from flask import Flask, render_template
3app=Flask(__name__)
4@app.route('/')
5def index():
6    animals = ['Dog', 'Cow', 'Lion', 'Panther']
7    # pass the animals list as a parameter in the render_template function
8    return render_template('index.html', animals=animals)
9if(__name__)=='__main__':
10    app.run(debug=True)


Now with this, all that's left is to access our list in the index file and render the animals in an unordered list.

let's do that ->

index.html
1...
2<body>
3    <div class="container">
4        <h2>Hello Flask app</h2>
5        <!-- Let's create our unordered list and render the animals--->
6        <ul>
7            {% for animal in animals %}
8            <!-- This is possible because of Jinja 2 --->
9            <li>{animal}</li>
10            {% endfor %}
11        </ul>
12    </div>
13</body>
14...
15

And now when we visit our local url and reload we can view our list of animals.

YouTube Tutorial

Flask Tutorial

Conclusion.

By no means have we exhausted what flask is capable of? There are very many powerful features of flask but this is a short introduction to get your engines started for flask exploration.

👍 Happy coding with Flask!

Share
NM

Newton Mbugua

Co-founder Software Engineer

Experienced software developer with nearly half a decade of expertise in full-stack development and a growing passion for data engineering. I have a proven track record of crafting high-quality, scalable software solutions using backend technologies like Node.js and Python, as well as frontend frameworks such as Next JS. I thrive in collaborative environments, bringing energy and a creative aspect to teams to turn innovative ideas into reality. I like to keep up-to date with new technologies and new ways of improving experiences online and continuously expanding my skill set through learning and experimentation.

Recent Posts


all rights reservedAesops©2024