A Beginners guide to building Applications in Flask.
Tags: python, tutorial, beginners, flask
Published: 2023-07-15 20:56:14

## Table of Contents
1. [Introduction](#a)
   - [What is Flask?](#a)
   - [Prerequisites](#b)
2. [Installations](#c)
   - [Setting up Virtualenv](#d)
   - [Installing Flask](#e)
3. [Building a Flask App](#f)
4. [Routing](#g)
5. [Dynamic Web Pages and HTTP Methods](#h)
   - [How to use Flask's Template System to Create Dynamic Web Pages](#i)
6. [Conclusion](#z)


**What Is Flask?**<a id = "a"></a>
Flask is a lightweight framework used to build fully featured web applications in Python. There are many frameworks used to build web applications in Python; however, Flask provides a different system from traditional web frameworks and makes it easy to build apps with just a few lines of code.
 
To understand how Flask works, there are terms you have to know as they contribute to Python’s functionality. Some of these terms are ;

- **Web Server Gateway Interface (WSGI):** WSGI is a specification for a universal interface between the web server and web applications. It is used to forward requests from a web server to a backend Python web application or framework.
- **Werkzeug:** Werkzeug is a collection of libraries that can be used to create a WSGI (Web Server Gateway Interface)-compatible web application in Python.
- **Jinja2** is a Python library that allows us to build expressive and extensible templates. It is used to build templates and integrate Python with non-Python code.

Basically, Flask handles requests and responses using the Web Server Gateway Interface (WSGI) and modifies the application according to the Jinja2 template engine. When building complex applications, you can take advantage of Python libraries to add advanced features to your web application.
 
In this article, we are going to look at all the major concepts involved in building a complete Flask application. To demonstrate these concepts, we would build a basic application that receives a request and dynamically sends a response to the browser.


**Prerequisites**<a id = "b"></a>
To follow this tutorial, you would need the following

1. An understanding of Python syntax and concepts,
2. Basic knowledge of HTML and CSS,
3. A local Python 3 programming environment and a browser.

**Installing Flask and setting up a virtual environment**<a id = "c"></a>
Before we get started with our application, you'll need to have `virtualenv` and `Flask` packages installed. These packages provide the necessary tools and libraries to set up and work with Flask applications.

**Virtualenv**<a id = "d"></a>
Virtualenv is used to create an isolated environment for your Python project. It ensures that your project has its independent instances of libraries, preventing compatibility issues with different library versions.
 
These are the steps you need to follow to install `virtualenv`:
 1. Create a folder where you want to store your project files.
 2. Open your command prompt or terminal and run the following command:

```
pip install virtualenv
```

 3.Once Virtualenv is installed, you would have to create your environment using  this command:

```
virtualenv venv
```
This will create a folder named `"venv" `
Please know that you can choose any name for your virtual environment. We are using_ venv _for the sake of this article.


 4.Next, you have to activate the environment you created;
If you are working with a Windows Operating System, you can use this prompt:

```
.\venv\Scripts\activate
```

For macOS or Linux users:
```
source venv/bin/activate
```
After activating the virtual environment, you should see the name of your environment in your terminal prompt, this shows that the environment is active.


**Installing flask**<a id = "e"></a>
To install the flask package, open your terminal or command prompt and follow these steps;

 1.Navigate to the directory where you want to create your Flask project. For example, if you want to create a folder named "_myfolder_", you would navigate to that location using the `cd` command. Assuming "_myfolder_" is located on your desktop, the command would be:
```
cd Desktop/myfolder
```

 2.Once you are in the right directory, you can run the following command to install Flask using pip:
```
pip install flask
```

 3.After executing the command, pip will download and install the Flask package along with its dependencies.

**Building the Flask Application**<a id = "f"></a>
Now that you have installed the required packages, you can now build your app by following these steps;

1. Create a new Python file with a `.py` extension to store your Flask code. You can choose any name for your file. For example, let's call it `app.py`.

2. Open the `app.py` file in your preferred text editor or integrated development environment (IDE).

3.Start by importing the Flask class from the `flask` module. This class provides the necessary functionality for creating a Flask application.

```python
from flask import Flask

```
4.Next, create an instance of the Flask class and assign it to a variable. This instance represents your Flask application. You can choose any name for the variable. In this example, we'll use `app`.

```python
from flask import Flask
app = Flask(__name__)
```
The Flask class is the core of a Flask application, and it provides the functionality necessary to handle HTTP requests and responses.

5. Define a route for your application. A route is a URL path that corresponds to a specific function. In this case, we'll define the root route ("/") using the `@app.route()` decorator.

A route decorator is used to define a route. It is usually followed directly by a function as it binds the route to the function. This means that when a user visits the root URL of your app, Flask will call the decorated function,” index()”

```python
from flask import Flask
app =Flask(__name__)

@app.route('/')
def index():
    return ' Hello World'
```

6. Usually, when a Python script runs, Python assigns the name "__main__" to the script. However, we can use an if statement to run the app once the condition ensures that the script is being executed directly by the Python interpreter and not imported as a module from another script. If we import another script, the if statement will prevent other scripts from running.

```python
if __name__ == "__main__":
    app.run(debug =True)
```

**Note:**
Setting your debug mode to true would allow all the changes made in your code to be applied to the app in the browser without having to run it over again 
 Here's a compilation of all the code steps;

```python
from flask import Flask
app =Flask(__name__)

@app.route('/')
def index():
    return ' Hello World'

if __name__ == "__main__":
    app.run(debug =True)
```



7. Save and run the file. To run your Flask app, open your terminal or command prompt, navigate to the directory where the `app.py` file is located, and run the path of your file using the Python command.


![a command to navigate to your file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkfpw2h5j148ip3sux7i.png)

Flask will start a local development server, and you'll see an output indicating that the app is running. You can now visit the root URL (usually http://localhost:5000/) in your browser to see the "Hello, World!" message displayed.
 

![flask runtime message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/01d1q927jub7vz542g49.png)

 While there are many useful pieces of information in this output, the most important for now is the fourth line, which shows that the application is running on your local host at the URL http://127.0.0.1:5000/. (Localhost refers to your local computer)

Open a browser and paste the URL, and you should see:

![a browser page displaying hello world](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33tzgl2yj9njd5mjmp1n.png)
Congratulations… you have successfully  built your flask app , which displays information on your browser,
 
However, in real-life applications, there are many pages and different functions that handle different events. This may seem overwhelming, but web frameworks have a system for dealing with this process, and the system is called routing.

**Routing**<a id = "g"></a>
Routing is used to map a specific URL to an associated function. For instance, in the previous code, the URL ( ‘/‘) was mapped to the index function using a route decorator, 

```
@app.route('/')
def index():
    return ' Hello World'

```
 
Routing allows you to declare different URLs or routes for different functions you may need. For example:

```
from flask import Flask
app =Flask(__name__)

@app.route('/')
def index():
    return ' Hello World'

@app.route('/product')
def Product():
      return 'This is our products page'

if __name__ == "__main__":
    app.run(debug =True)

```


In the preceding code, we created a new function called product," which is mapped to the URL "`/products"`. This function will be called when a user visits the `/product` URL and returns the string _' This is our products page'_.

The first route is '/', which is the root URL. The index() function is associated with this route and will be called when a user visits the root URL. It returns the output of the home function 'Hello World'.

![a browser page displaying hello world](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ge3hf05shfj5pbfct96c.png)


Accordingly, the URL `127.0.0.1:5000/product` displays the output of the product function.

  

![a browser page displaying this is our products page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlyjyhqsglw5ywqlo1nu.png)


**Dynamic web pages and HTTP methods**<a id = "h"></a>
 
The route decorator `@app.route()` typically accepts the URL as the first parameter. However, it can also accept a list of HTTP methods as a second parameter.

**HTTP methods** are instructions clients (such as web browsers) use to communicate with servers to perform specific operations. Each method defines an action to be performed on a resource. Some common HTTP methods are;
 
**GET**: is used to retrieve data from a server.
**POST**: This method sends data to the server from a webpage. It’s like submitting a form or sending information to be processed or stored.
**HEAD**: Retrieves data from the server just like the GET method but doesn’t receive the actual content. It is like asking for metadata about a resource.
**PUT**: Replaces an existing resource on the server with the updated version.
**DELETE**: Deletes the target resource from the server

By default, the Flask route responds to GET requests. unless the route decorator explicitly mentions which HTTP methods it should honor. To demonstrate how the POST method works with URL routing, Now, let us first create an HTML form and use the POST and GET methods to retrieve and send form data to a URL.

**HTML code**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="http://localhost:5000/login">
    <p> Enter name:</p>
        <p><input type="text" name="name"></p>
        <p><input type="submit" value="submit"></p>
    </form>
</body>
</html>
```
 
Using this code, we created an HTML form that asks for a name and submits the inputted value to the URL "http://localhost:5000/login" which would be defined in the Python file.


**Python code**

```python
from flask import Flask, request, redirect, url_for, render_template


app = Flask(__name__)


@app.route('/')
def home():
    return render_template('index.html')


@app.route('/success/<name>')
def success(name):
    return 'Welcome %s' % name


@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        user = request.form['name']
        return redirect(url_for('success', name=user))
    else:
        user = request.args.get('name')
        return redirect(url_for('success', name=user) if user else url_for('home'))


if __name__ == "__main__":
    app.run(debug=True)
```


Here’s a breakdown of the Flask code;
**Lines 1 and 2:** Imports the Flask class and create an instance of the class for our app.

**Line 3-5:** The code creates a route decorator (@app.route()) that binds the URL path /success/<name> to the success function. 

**PS**, The <name> variable used is called a URL parameter. , URL parameters, are used to pass dynamic data within the URL of a Flask application. They capture specific values from the URL and make them accessible for use within Flask routes and functions.
The success function returns a string that displays the inputted name in place of a namespace (%s).

**Line 4- 8:** The route decorator binds the URL path (/login) to the login function. The function also handles both GET and POST requests.
 
![a page that shows a form that accepts an input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fu3b4gy21538pif1pvqa.png)
The POST request retrieves the value submitted through the name form field using the `request. form['name']`. (which is the name we gave to our input in the form). The user value is then passed to the success route using the `redirect` function and the `url_for` function, which generates the URL for the success route.
 
![an ouput that welcomes a user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dymge6rbz1sbb0t1updj.png)
The GET request retrieves the value of the name query parameter from the URL using `request.args.get('name')`. Again, the user value is passed to the success route using `redirect` and `url_for`.

**How to use Flask's template system to create dynamic web pages**<a id = "i"></a>
 
There may be instances where you would want to modify the output on your webpage without necessarily changing the output message from your function. You may also want to create a more complex output that can’t be satisfied with a simple return statement.
 
Flask has a function called `render_template` that handles such occurrences on your app. `render_templates` allows you to create and use HTML pages in the form of templates for your web app. This replaces the string output, which is limited, and allows you to create more interactive web pages in Flask.
 
To make use of the `render_template` function, we have to create a folder in your work environment where the `render_template` function can fetch the.html file(s) you want to make use of. This folder should always be named "templates," as this function looks for a template (HTML file) in the templates folder. 

In a case where you can’t name the file as directed, you would have to direct the function to your preferred folder by initializing the template variable in the instance of the flask class.

```python
app = Flask(__name__, template_folder="templates")
```

**Home Page**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>This is our home page</h2>
</body>
</html>
```


**About page**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>This is out about page</h2>
</body>
</html>
```

**Flask code**

```python
from flask import Flask, request, redirect, url_for, render_template


app = Flask(__name__)


@app.route("/")
def home():
    return render_template("home.html")
   
@app.route("/about")
def about ():
 return render_template("about.html")
if __name__ == "__main__":
    app.run(debug=True)

```


In our Flask application, we have imported the _render_template()_ method from the Flask module. Most of the code remains the same however, on line 7, we have modified the return statement. Instead of returning a plain string or response, we now use _render_template("home.html")_. This instructs Flask to look for the "home.html" template file in the "templates" folder and render it as the response. 

![a page showing this is our home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rf800p7fo0fzmtp9msd7.png)

This also applies to the about function. 


![a page displaying this is our about page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eg9jqwjbwxxos8690fs8.png)
By utilizing render_template(), we can easily incorporate HTML templates into our Flask application, separating the presentation logic from the rest of the code. This allows us to create dynamic and interactive web pages by combining HTML with Flask's powerful features. You can also style these pages with CSS language to improve the visual appeal of your site.


**Conclusion** <a id="z"></a>
Throughout this guide, we covered the basics of Flask, including how to set up a Flask project, define routes, handle HTTP methods, and use Flask's template system. With this knowledge, you can start building your own Flask applications, adding more functionality as you progress.