An Introduction to Flask: A micro-framework

Nitish Sharma
Analytics Vidhya
Published in
8 min readAug 28, 2020

Hey there! Thinking of developing a web application using python? Probably you must be looking for a framework or if you’re not aware, A Framework is a piece of code which makes developers’ life easier. It lets the developer focus on the high-level functionality of the application and handles the low-level functionality by itself by providing some reusable or extensible codes. In this article, I’m going to discuss one such framework, made for creating web applications in python called FLASK.

What is Flask?

According to the official website of Flask, It’s a python micro-framework. By micro, it doesn’t mean that it is less functional or the whole application should fit in one single python file(although we will see that it’s possible). It’s a highly extensible framework with lots of extensions available by the community but the idea is to keep the core simple. By default, Flask doesn’t include functionalities like database abstract layer, form validation, etc. but these can be added by using extensions.

In this article, we’ll see how to get started with Flask, and we will create a very basic book listing application. (Let’s call it Flask_Bookshelf)

Before jumping to the app I’ll first discuss some basic concepts like Installing Python on your computer, creating a virtual environment (recommended for better management of dependencies for your projects) and, Installing Flask. Let’s see them one by one:

Installing Python

You can visit the official website (https://www.python.org/downloads/) of python to download the latest stable release of python installer corresponding to the OS you’re using and install it.

Use python — version to verify if it’s successfully installed or not.

Creating and activating a virtual environment

Virtual Environments are a group of python libraries, one for each project. Working on a virtual environment is recommended because your different projects may need different versions of python or python dependencies and using one version of a library in one project can break the compatibly of some other project.

Note that I’m using python 3 throughout this article which comes up with ‘venv’ module by default for creating virtual environments. But if you are using python 2 you have to install an additional module called ‘virtualenv’ to create a virtual environment. You can check the official documentation of Flask Installation for more details on this.

Steps to follow:

  • Make your project directory. Here I’m naming it flask_bookshelf
$ mkdir flask_bookshelf
  • Change your working directory to the one just created
$ cd flask_bookshelf
  • Create a virtual environment with the name ‘venv’. You can name it whatever you want.
$ python3 -m venv venv

(Notice that it will create a venv directory in the root)

  • Activate the environment
$ source venv/bin/activate or $ . venv/bin/activate

(now you will notice $ (venv) at the beginning of your terminal, which means that you are under venv activated virtual environment)

Installing Flask

Here I’m using PIP to install flask, So, to follow along, make sure PIP is installed on your computer. Within the activated venv run the following command

$ pip install Flask

Okay! we are now ready with the setups, let’s take a moment to understand what we are building, How our Flask_Bookshelf will look like and what are the things we can do with it.

Our app will be a very basic book listing app. For simplicity I’m not going to connect this with any database instead I’ll be using a CSV file to store our book details. Later through another article, I may discuss how to connect a Flask Application to any SQL or NoSQL database, but for this article, we are not using any database. I am also not going to discuss how to add, delete, or modify the books’ details in this article. But I assure you that after going through this article you will be having a clear idea of how a flask application works.

We will be creating the following two endpoints for our application, which will basically display the same content on the web page:

GET /GET /home

Our Project Structure will look like this:

project structure

This is a basic structure followed by Flask. Here we have two directories inside src i.e. static and template. Static holds all the static files like stylesheets, assets(images, videos, fonts, etc.) used in the projects, etc. whereas the templates directory holds all the HTML pages which will get rendered onto the browser.

Now let’s get started with our coding.

Create a directory named ‘src’ in the root directory. Basically this will hold our whole application.

Inside the src directory create __init__.py file with the following content. It will tell python that src is a package as well as it will work as the factory for our application.

# __init__.pyfrom flask import Flaskapp = Flask(__name__)
@app.route(‘/’)def home(): return “WELCOME TO FLASK_BOOKSHELF”

This is how the most basic and complete Flask app looks like. To verify, run this using the following commands:

$ export FLASK_APP=src$ export FLASK_ENV=development$ flask run

You will observe something like this in the terminal:

* Serving Flask app “src” (lazy loading)* Environment: development* Debug mode: on* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 272–048–342

Now go to http://127.0.0.1:5000/ in your browser and you will see the welcome message which means that your app is successfully running.

Now let’s understand this piece of code and the commands we have used to run this.

  • First, we have imported the FLASK class in the first line of our code
  • We created an instance of the FLASK class. The first argument is the name of the application’s module or package. This is needed so that Flask knows where to look for templates, static files, etc. That’s why here we have used __name__.
  • We then used route() decorator to set the URL which will trigger our method home(), In flask, we call it a view.

To run the application we have used three commands. In the first two commands, we are setting two environment variables FLASK_APP and FLASK_ENV. (I have used export to set the variable as I’m using Mac OS, for windows use set for the same)

  • Setting up FLASK_APP env variable will ensure the terminal to look into a Flask App instance in the module/package we assign to it.
  • FLASK_ENV is another variable and setting this to ‘development’ will enable DEBUG mode while running the application. By running on debug mode you don’t need to restart or rerun the application every time you change something, you just need to reload the browser and the changes will automatically reflect.

So, from here you can leave it as it is and follow the rest of the coding.

After setting these env variables we are using flask run to run the application. By default, it runs the server at port 5000.

Currently, our app just displays a welcome message. Let’s modify our home() method to render an HTML template (src/templates/home.html) to show the list of books available, reading it from a CSV file (books.csv).

# __init__.pyimport csvfrom flask import Flask, render_templateapp = Flask(__name__)
def get_books(): books = [] with open(‘books.csv’) as book_file: reader = csv.reader(book_file) for row in reader: books.append(row) return books
@app.route(‘/’)def home(): books = get_books() return render_template(“home.html”, books=books)

Now notice that I have imported the csv module from python to read the books.csv file. I have created a method get_books() for that, which is returning a list of books (actually a list of lists where each list is containing book_id, title, and author). This is how our csv file looks like:

001,Notes from a Small Island,Bill Bryson002,The Lord of the Rings,J.R.R. Tolkien003,The Control of Nature,John McPhee004,Coming Into the Country,John McPhee005,The Heidi Chronicles,Wendy Wasserstein006,The Power of One,Bryce Courtenay

Now in the home method, we are returning something called render_template(). Its a method provided by Flask which takes a template name or a list of templates from the template folder and renders it into the browser whenever called. Here we are passing home.html to get rendered. We can also pass some key parameters to it which will be available in the context of the template. Here I’m passing books as the key argument. We will see how to use it inside our template.

So, now we need our template home.html. Let’s create that.

<!-- home.html -->
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> <title>FLASK_BOOKSHELF</title></head><body> <center> <div> <h1>WELCOME TO FLASK_BOOKSHELF</h1> <table> <tr> <th>BOOK ID</th> <th>TITLE</th> <th>AUTHOR</th> </tr> {% for book in books %} <tr> <td>{{ book[0]}}</td> <td>{{ book[1]}}</td> <td>{{ book[2]}}</td> </tr> {% endfor %} </table> </div> </center></body></html>

After looking into it you may find it a bit different from a normal HTML file. Like I have used {% for book in books %}{% endfor %} for looping the books list passed as a parameter from the view. Also, I have used {{ book[i] }} to access book variable. This is actually a Jinja2 template feature that is used by flask to render templates. You can read more about it here.

Now just reload the page in the browser and voila! We have our list of books displayed on the page. But it seems very simple. Let’s make it a bit attractive by adding a stylesheet (src/static/styles.css).

/* styles.css */
h1 { color: teal;}table, th, td { border: 2px solid teal; text-align: center;}th, td { padding: 15px;}th { background-color: teal; color: white;}

Reload the page again and you will see a bit better and cleaner look of the page. I’m not adding lots of styles here, the motto is just to show how we can use the static directory to add styles to our templates. Our current output:

the output of our flask_bookshelf running

It seems that we’re done with our book listing app, but holds on we were going to create two endpoints. Remember? Don’t worry, as we are going to display the same view for both the endpoints, we don’t need to do much, just add @app.route(‘/home’) below the current route ‘/’ and now Flask will render the same home() view for both the routes. The __init__.py will now look like this:

# __init__.py
import csvfrom flask import Flask, render_templateapp = Flask(__name__)def get_books(): books = [] with open(‘books.csv’) as book_file: reader = csv.reader(book_file) for row in reader: books.append(row) return books
@app.route(‘/’)@app.route(‘/home’)def home(): books = get_books() return render_template(“home.html”, books=books)

Congratulations! We’re done with our very basic book listing flask app. Let’s summarize what we have learned throughout:

  • Creating & activating the virtual environment using the venv module in python3.
  • Installing Flask.
  • Creating endpoints for our application.
  • Using templates in the flask app.
  • Using Static Files in the flask app.
  • Running a flask app

Our app is very elementary and it just shows the basic structure of a flask application but a lot more can be done using flask. There are lots of things like connecting our app to a database, adding authentications, modularizing project structure using Blueprint, Adding more endpoints for updating, deleting, or adding books on our list, etc. I may discuss a few of them in my later articles but if you want to learn on your own you can anytime check the official flask documentation.

Thank you for reading. Please let me know your feedback in the comments.

--

--

Nitish Sharma
Analytics Vidhya

Senior Consultant - Application Developer at Thoughtworks, India