Photo by Glenn Carstens-Peters on Unsplash

Building Your First Flask App

Babatunde Koiki
The Startup
Published in
7 min readApr 17, 2020

--

Photo by Austin Distel on Unsplash

Objectives of this article

  1. Know what Flask is all about
  2. Understand what virtual environment is and how to create one in Python.
  3. Build a one page app with flask
  4. Adding HTML to your app.
Flask is fun.

Flask Web Development

Flask is a Python Framework for Back End Web Development. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

It is commonly referred to as a micro-framework when compared to Django though you can build a strong and great app with it.

While defining Flask above, I used some terminologies, let me explain them now.

  1. WSGI web application framework: The Web Server Gateway Interface (WSGI, pronounced whiskey) is a simple calling convention for web servers to forward requests to web applications or frameworks written in the Python programming language.
  2. Werkzeug: Werkzeug is a comprehensive WSGI web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries. Flask wraps Werkzeug, using it to handle the details of WSGI while providing more structure and patterns for defining powerful applications.
  3. Jinja : Jinja, also commonly referred to as “Jinja2” to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response. Jinja2 is useful because it has consistent template tag syntax and the project is cleanly extracted as an independent open source project so it can be used as a dependency by other code libraries.

Virtual Environment

A Virtual Environment is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects It enables multiple side-by-side installations of Python, one for each project.

You can check the python’s documentation on virtual environment.

Steps in Enabling Virtual Environment

  1. Open a terminal, if you’re using Windows you can open command prompt instead or your IDE’s terminal.
  2. Setup the pip package manager.
  3. Install the virtualenv package.
  4. Create the virtual environment.
  5. Activate the virtual environment.
  6. Deactivate the virtual environment.
  7. Optional: Make the virtual environment your default Python.
  8. More: Python virtualenv documentation.

If you’re just installing Python, download and install Python, ensure you install it correctly.

Setting the pip package manager :

If you’re using Windows:

py -m pip --version
## You should get something like the one below.
## pip 9.0.1 from c:\python36\lib\site-packages (Python 3.6.1)
##You can upgrade your pip by writing
py -m pip install --upgrade pip

If you’re using Mac or Linux:

python3 -m pip install --user --upgrade pippython3 -m pip --version
## pip 9.0.1 from $HOME/.local/lib/python3.6/site-packages (python 3.6)

Installing Virtualenv

python3 -m pip install --user virtualenv # For Mac and Linux userspy -m pip install --user virtualenv # For Windows user

Creating the virtual environment

py -m venv env # For Windows users
python3 -m venv env # For Mac and Linux users

The second argument env is the name of the virtual environment which can be anything. All of this should be done in your working directory.

Activating the virtual environment

source env/bin/activate #For Mac and Linux users
.\env\Scripts\activate #For Windows users.

Note : env used in the command above should be replaced with whatever you named your virtual environment.

To confirm that you’re in the virtual environment

which python # For Windows users
.../env/bin/python
where python # For Mac and Linux users
.../env/bin/python.exe

Deactivating your virtual environment

To leave the virtual environment, just type deactivate.

deactivate

Next is to install the necessary libraries

For this project we need to install flask

pip install flask
Image you should get after installing flask.

To confirm that you have flask installed, type in your terminal

python “import flask; print(flask.__version__)”

#1.1.2

If you noticed what I did above, I used the python keyword, which opens ther shell for me, but I added some parameters seperated by semi-colon in a string which is what I want to write in the shell, the semi-colon breaks each expression line by line. This is useful if I want to just confirm something in this case if flask is installed.

Now we’ve confirmed that we have flask and it’s dependencies installed.

Let’s build our Flask App

In your working directory, create a new python file and save it. I’ll be saving my file app.py

Next is to run the app.

As we can see we’ve built our flask app.

Let’s look at each line deeper

In line 1: We import the Flask from flask which is what we used to create our app.

In line 2: We created our class decorator and save it as Flask, this is a standard convention.

In line 3: We used the app to decorate our function. You can read more on decorators. We route the decorator to the home page of the site. I could route it to the about endpoint by doing app.route(‘/about/’) .

In line 4: We created a function and called it home which has no parameter.

In line 5: We returned Hello world! in the function.

Lastly, we used the run method on our decorator.

In the terminal

I used the set keyword (If you’re using Mac or Linux, use export instead)

I set the FLASK_APP to the script that runs my app excluding the extension which will always be .py note the convention. Uppercase, no space, note that all of this must be done in the root directory of your project which your run file is. Note that by default FLASK_APP in the configuration of flask variable is set to app or wsgi so if you're running your script with any of this two you might not need to set it.

I also set FLASK_ENV to development, note that in this case we’re just developing and not deploying, note by default it’s in the production

All what we set in the terminal are configurations that flask will use to run our app.

Lastly, I run the app.

You can see the url of the app

Our Simple App

Let’s Add HTML To Our Page

Flask uses Jinja2 engine. Firstly, we create a templates folder and put all our HTML codes in it.

the medium folder

In our .py file, we’ll write

In the .py file

You’ll notice some changes in the file now.

  1. We import an additional function, called render_template which we use to render our HTML files. It’s what Jinja uses to get the html in our view function.
  2. Above our home function we have 2 decorators. What these do is that the page has two endpoints. if I go to the home endpoint, I’ll get the same page.
  3. There’s a new decorator(route), this routes the function to the about endpoint. And the about function which we use to perform this.

In the first html code, home.html we have

home.html
  1. Within the body tag, is what we see on the browser
  2. The head tag describe the meta data of the web page.
  3. In between the body tag, I put the h1, p, a and footer tags.
about.html

Next is for us to run the app.

Since we’ve written some file which is used in the project outside the .py file, we need to run it again. But all we need to do is type flask run in the terminal

home page without any endpoint
home page with endpoint
about page

The first two images are the same because the home view function has two endpoints ‘/’ and ‘/home/’. Note that the presence of the trailing back slash in the route from the view function allows flexibility, i.e I can decided to add it or not in the browser.

Con

--

--

Babatunde Koiki
The Startup

I’m a back enddeveloper experienced in building APIs and web applications, I’m also an AI/ML/DL/DS Engineer and a JavaScript enthusiasts, lover of ReactJS.