DEV Community

Cover image for Getting started with Flask
Faruq Abdulsalam
Faruq Abdulsalam

Posted on • Updated on

Getting started with Flask

Hello there, welcome to the Flask world. In this series, you are going to learn how to build a web application using the micro web python framework Flask. Let's get started!

The code for this series has been made available on Github. However, I strongly advise you to follow the tutorial and create the application with what you will learn here rather than cloning the repo straightaway. You can then choose to access the repo at the end.

The Github repo can be accessed via this link.

In this part of the series, you are going to learn how to set up your Flask project and display a simple message in your browser. Let's get started.

Setup

I’ll assume that you already have python installed on your machine. If you don't, you can download and set it up via this link. Please ensure you download the latest version of python. (Python 3.97)

Open the Command Line on Windows, Terminal on Mac, and Linux and navigate to the directory where you want to store the project and create a new directory

mkdir flask
Enter fullscreen mode Exit fullscreen mode

Move into the new directory

cd flask
Enter fullscreen mode Exit fullscreen mode

Create a Virtual environment.

It is recommended to always create a virtual environment before you start your project. This helps you to separate the packages you use in this application from other applications; any change you make here won't affect the same package in another application on your system. To create a virtual environment on your system; run this command:

For mac/unix users: python3 -m venv env
For windows users: py -m venv env
Enter fullscreen mode Exit fullscreen mode

After creating the environment, activate it by running :

For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

You can deactivate it by simply running the command below, but you don't have to deactivate it yet.

deactivate
Enter fullscreen mode Exit fullscreen mode

Installing Flask

First you have to install Flask,

pip install flask
Enter fullscreen mode Exit fullscreen mode

You are officially done with setting up your system for the flask project 🤝, now let us proceed to the project setup itself.

Setting up the project

Create a new directory inside the flask directory

mkdir core
Enter fullscreen mode Exit fullscreen mode

Move into the new directory

cd core
Enter fullscreen mode Exit fullscreen mode

Next create two new files __init__.py and views.py with the commands:

touch __init__.py
Enter fullscreen mode Exit fullscreen mode
touch views.py
Enter fullscreen mode Exit fullscreen mode

init.py

from flask import Flask

app = Flask(__name__)

from core import views
Enter fullscreen mode Exit fullscreen mode

In the created script, the Flask class is imported from the installed flask package, and a __name__ variable is passed to it and they are finally assigned to an app variable.

The __name__ variable which is automatically set by python helps to get the name/location of the module in which the __init__.py script is called. In this case, __name__ is core because the script file __init__.py is located in the core directory and this tells Flask where to look for resources such as templates and static files. You will understand this better when the application starts becoming large and new packages are created to separate concerns.

Finally, the views.py module is imported from the project directory into the script. You must have noticed that the import is done at the bottom of the file, not at the top. The reason for this is to prevent the issue of circular imports. The routes module is being imported into the script but you will also need to import the app variable in the views.py module which might lead to an error due to cyclical dependencies.

views.py

from core import app

@app.route('/')
def index():
    return 'Hello Ace'
Enter fullscreen mode Exit fullscreen mode

The app variable declared in the __init__.py script is imported here and used as a decorator. The line @app.route('/') is a python decorator made available by flask and this is used to modify the index function called below it and to assign the URL "/" to the function. Thus, the index function gets executed whenever a user navigates to the specified URL mapped to it.

base.py

To finish up, return to the root directory flask and create a base.py file

cd ..
Enter fullscreen mode Exit fullscreen mode
touch base.py
Enter fullscreen mode Exit fullscreen mode

and import the app variable into the script.

from core import app
Enter fullscreen mode Exit fullscreen mode

running the application

To run the application, you need to export the script in the root directory base.py

export FLASK_APP=base.py
Enter fullscreen mode Exit fullscreen mode

then run:

flask run
Enter fullscreen mode Exit fullscreen mode

Navigate to the URL http://127.0.0.1:5000/ in your web browser and the page below should be displayed.
Index function page

To run the flask application whenever you open up a new terminal, you have to always export the script in the root directory. The solution to this is to create an environment to store the assignment of the script to the FLASK_APP. To do this you need to install the python-dotenv package.

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Next, create a .flaskenv file in the root directory and store the assignment of the script to the FLASK_APP in it:

touch .flaskenv
Enter fullscreen mode Exit fullscreen mode
FLASK_APP=base.py
Enter fullscreen mode Exit fullscreen mode

Note: Please dont forget the '.' infront of flaskenv. If you do, this process won't work.

Now, whenever you open a new terminal, you can just go ahead and run the application with:

flask run
Enter fullscreen mode Exit fullscreen mode

Note: To run the application without getting any error.You need to always be in the root directory before running the command flask run

The project setup is done, this should be the current look of your directory.
Current directory

Templates

Flask uses jinja2 template format by default.

index.html

Create a folder named templates in the core directory and create a file named index.html in it.

cd core
Enter fullscreen mode Exit fullscreen mode
mkdir templates
Enter fullscreen mode Exit fullscreen mode
cd templates
Enter fullscreen mode Exit fullscreen mode
touch index.html
Enter fullscreen mode Exit fullscreen mode

and put these basic lines of code in your HTML file.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Test HTML</title>
    </head>
    <body>
        <h1>{{greet}}</h1>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here, a value will be assigned to the greet variable included in the h1 element whenever the index.html file is being rendered. This will be explained better below.

views.py

from flask import render_template
from core import app

@app.route('/')
def index():
    greeting="Hello there, Ace"
    return render_template('index.html', greet=greeting)
Enter fullscreen mode Exit fullscreen mode

Next, some changes will be made to the views.py file. You have to import the render_template function from the flask package. The function renders the template file index.html and assigns the value of the greeting variable to the greet variable in the HTML file.

You can test this by running the application with

flask run
Enter fullscreen mode Exit fullscreen mode

Then open your web browser and navigate to the same URL as before http://127.0.0.1:5000/. You should see your h1 element with the value of the variable greeting declared in views.py.
End of series

We have finally come to the end of the first part of the series. With the simple examples given above, I am sure you can easily set up a new flask application for your project and also pass data from the backend to template files.

In the next part of the series, we'll start creating our web application. Things will start getting complex but I'll make sure I break it down as much as I can. See you there!! Cheers!!!

If you have any questions, feel free to drop them as a comment or send me a message on Linkedin or Twitter and I'll ensure I respond as quickly as I can. Ciao 👋

Discussion (0)