Getting started with Flask
Tags: python, webdev, programming, tutorial
Published: 2021-11-20 08:26:08

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](https://github.com/Faruqt/Flask-Complete-Tutorial/tree/master).

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](https://www.python.org/downloads/). 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 
```javascript
mkdir flask
```
Move into the new directory
```javascript
cd flask
```
###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:
```javascript
For mac/unix users: python3 -m venv env
For windows users: py -m venv env
```
After creating the environment, activate it by running :
```javascript
For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate
```
You can deactivate it by simply running the command below, but you don't have to deactivate it yet.
```javascript
deactivate
```
###Installing Flask
First you have to install Flask,
```javascript
pip install flask
```
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
```javascript
mkdir core
```
Move into the new directory
```javascript
cd core
```
Next create two new files `__init__.py` and `views.py` with the commands:
```javascript
touch __init__.py
```
```javascript
touch views.py
```
#### __init__.py
```javascript
from flask import Flask

app = Flask(__name__)

from core import views
```
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
```javascript
from core import app

@app.route('/')
def index():
    return 'Hello Ace'
```
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
```javascript
cd ..
```
```javascript
touch base.py
```
and import the app variable into the script.
```javascript
from core import app
```
####running the application
To run the application, you need to export the script in the root directory `base.py`
```javascript
export FLASK_APP=base.py
```
then run:
```javascript
flask run
```
Navigate to the URL `http://127.0.0.1:5000/` in your web browser and the page below should be displayed.
![Index function page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqzhipiqp3dg8aiswqmi.png)

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.
```javascript
pip install python-dotenv
```
Next, create a `.flaskenv` file in the root directory and store the assignment of the script to the `FLASK_APP` in it:
```javascript
touch .flaskenv
```
```javascript
FLASK_APP=base.py
```
**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:
```javascript
flask run
```

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3iz100adf0oefbectnle.png)

#Templates
Flask uses [jinja2](https://flask.palletsprojects.com/en/2.0.x/templating/) template format by default.
###index.html
Create a folder named `templates` in the core directory and create a file named index.html in it.
```javascript
cd core
```
```javascript
mkdir templates
```
```javascript
cd templates
```
```javascript
touch index.html
```
and put these basic lines of code in your HTML file.
```javascript
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Test HTML</title>
    </head>
    <body>
        <h1>{{greet}}</h1>
    </body>
</html>
```
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
```javascript
from flask import render_template
from core import app

@app.route('/')
def index():
    greeting="Hello there, Ace"
    return render_template('index.html', greet=greeting)
```
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 
```javascript
flask run
``` 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9azrt11hk2zd3ngc2c8b.png)
 
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](https://www.linkedin.com/in/faruq-abdulsalam) or [Twitter](https://twitter.com/Ace_II) and I'll ensure I respond as quickly as I can. Ciao 👋