Beginners guide to setting up and running Flask web server
Tags: python, flask, web, server
Published: 2021-06-07 16:24:23

In this blog post, we will learn how to set up a web server using flask.

## Introduction

<a href="https://flask.palletsprojects.com/en/2.0.x/" target="_blank">Flask</a> is a Python web framework built with a small core and easy-to-extend philosophy.

## Getting started

Before getting started, let us make sure we have python3 installed in our system.
Follow <a href="https://www.python.org/downloads/" target="_blank">Python download </a> link to get python installed in your system. Once the python installation is completed, let start with creating a server.

Before proceeding with the setup, let us create a folder named flask-app. Run the below command to make a folder.

```bash
$ mkdir flask-app
```

Now cd into the newly created `flask-app` folder.

```bash
$ cd flask-app
```

Now let us set up a virtual environment using `python3` for the app. To set up a virtual environment, let us run the below command.

```bash
$ python3 -m venv env
```

After creating a virtual environment, we need to activate the environment.

```bash
$ source env/bin/activate
```

Now, finally, we can start with creating a web server using a flask.

### Setting up flask

As python Flask is an external module, to start working on it, we need to install it.

```bash
$ pip install Flask
```

Now, let us create a file called `app.py` in the root directory of our project. You can use the terminal or code editor of your choice.

```bash
$ touch app.py
```

Once the file is created, let us add the following lines of code in the file.

```python
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello world</p>"

```

### Running flask server

To run the application, use the flask command or `python -m flask`. Before you can do that, you need to tell your terminal the application to work with by exporting the `FLASK_APP` environment variable:

```bash
export FLASK_APP=app
$ flask run
 * Running on http://127.0.0.1:5000/
```

Finally, our server is running on `Port 5000`. Go to your browser and open [localhost:5000](localhost:5000). You should see Hello World in the browser. How cool is that? Amazing right?

![Hello Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b00v8mdc8k8i2ddcfcyd.png)

If you check the flask code

```python
@app.route("/")
def hello_world():
    return "<p>Hello world</p>"
```

We are saying in the code above that if anyone hits `/` in the browser. Then the flask app will run the `hello_word` function. Since we were returning `<p>Hello world</p>`, this gets rendered in the browser.

### Rendering index.html and CSS using flask

So far, we returned a string from the server. In this section, let us try to return HTML, CSS, Javascript files when we hit `/`in the browser. To do that, we need to create two folders named `static` and `templates`

```bash
$ mkdir static
$ mkdir templates
```

We will place all the views file, HTML files in the template folder; js and CSS files inside the static folder.

Let's create an `index.html` file inside the `template` folder and add the snippet.

**index.html**

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="static/index.css" />
    <link
      rel="shortcut icon"
      href="{{ url_for('static', filename='favicon.ico') }}"
    />
  </head>
  <body>
    <div>
      <p>Pratap</p>
    </div>
    <script src="static/index.js"></script>
  </body>
</html>
```

Also `css` and `js` file inside `static` folder.

**index.css**

```css
body {
  background-color: red;
}
```

**index.js**

```js
console.log("I am running");
```

If you check the `index.html` file

```html
<!-- Loading the css file using this line -->
<link rel="stylesheet" type="text/css" href="static/index.css" />

<!-- Linking the javascript file using this line -->
<script src="static/index.js"></script>
```

Now let's update our `app.py` file and some more code there.

```python
from flask import Flask, render_template

app = Flask(
 __name__,
 template_folder="./templates",
 static_folder="./static",
)

@app.route("/")
def hello_world():
    return render_template('index.html')
```

If you observe the code above. We have updated the `Flask` function. We let the flask know where it should load the `templates` and `static` files.

```python
app = Flask(
 __name__,
 template_folder="./templates",
 static_folder="./static",
)
```

> By default Flask will look for `template` and `static` folders.

And then, we also updated the `/` route we return `render_template(index.html)`. So, the flask app will load the `index.html` file and pass it to the `render_template` function.

```python
@app.route("/")
def hello_world():
    return render_template('index.html')
```

Re-run the flask app and hit [localhost:5000](localhost:5000) from the browser. Alas! The HTML file is now loading. Amazing!

I hope you are going well.

### Working with JSON

Until now, we are only working on HTML snippets. In this section, let's return a JSON object.

```python

from flask import Flask, render_template, jsonify

app = Flask(
 __name__,
 template_folder="./templates",
 static_folder="./static",
)


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


@app.route("/json")
def json_response():
    response = {"name": "Pratap", "age": 24}
    return jsonify([response])
```

So if look `json_response()` function carefully we are now returning a `dictionary`. We than pass it to `jsonify()` function which we imported from `Flask`

```python
@app.route("/json")
def json_response():
    response = {"name": "Pratap", "age": 24}
    return jsonify([response])
```

If you re-run the application and hit [localhost:5000/json](localhost:5000/JSON) from the browser. You will see a JSON object being displayed in the browser.

![Hello Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgt9wa9tbg3qxxkx551v.png)

### Turning on auto-reload

Until now, after making each change, you need to restart the app. We can also tell the `flask` app to restart after we make any changes. We need to update the `app.py` and add the following snippet at the bottom of the file. We have added a condition that if we are running the file directly, add `debug=True`. This will make sure to run the app in **debug mode**

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

Now, when running the app, we can run the app by running it in the terminal.

```bash
$ python app.py
```

We can also mention which port to run on. Currently, it's running on 5000 port by default.

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

### Folder strucure

![Flask folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i1qvwtdwikc72o6vjjsi.png)

> **Things to remember**
>
> 1. To build a python web application, we need to import the Flask module.
> 2. We need to pass the name of the current module, i.e., **name**, as an argument into the Flask constructor.
> 3. The `route()` function of the class defines the URL mapping of the associated function.
> 4. `app.run()` method is used to run our **Flask Application**.

## To sum it up

This is it from this article. I hope I'm able to give you an overview of how the Flask application work. You can find the source code <a href="https://github.com/Pratap22/flask" target="_blank">here</a>.

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter [here](https://pratap.substack.com).

Please don't hesitate to drop a comment here if I miss anything. Also, let me know if I can make the post better.