Getting Started with Flask
Tags: webdev, flask, python
Published: 2021-10-26 04:26:42

---
title: Getting Started with Flask
published: true
date: 2021-10-12 15:44:40 UTC
series: Flask Mini Tutorial
tags: WebDevelopment, Flask, Python
canonical_url: http://iread.ga/posts/54/getting-started-with-flask
---

In this blog, we're going to talk about what is Flask and how to get started with Flask. We'll create a simple Hello World application and see how we can write an application that is more extensible than a simple one.  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jjo9lt0vx5pk0bokn8d.png)


# **Introduction**

Flask is a _simple_, _easy-to-use_ **microframework** for Python that can help build scalable and secure web applications. It's easy to set up and is being supported by a large community. Thus it is considered quite easy to get started with Flask rather than other Python web frameworks like Django. It's also flexible enough, so if you want more functionality, you can add more extensions.  
 

# **Installation**

Before you install Flask, make sure you have Python installed in your system. You can check using the `python` command as given below:

```bash
$ python
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 
```

If you didn't get similar output, download and install Python from [here](https://www.python.org/downloads/).

Next, we are going to create virtual environment using virtualenv. Python now ships with pre-installed virtualenv library. So, to create a virtual environment, you can use the below command:

```bash
$ python -m venv env
```

The above command will create a virtual environment named `env`. Now, we need to activate the environment using the command:

```bash
$ . env/Scripts/activate
```

To verify if the environment has been activated or not, you can see `(env)` in your terminal.

After you have activated the environment, you are ready to install Flask with the below pip command:

```bash
$ pip install Flask
```

This will install Flask and few other dependencies that come with it. To check what all has been installed, you can run the below command:

```bash
$ pip freeze

# OUTPUT
click==8.0.3
colorama==0.4.4
Flask==2.0.2
itsdangerous==2.0.1
Jinja2==3.0.2
MarkupSafe==2.0.1
Werkzeug==2.0.2
```

We can also put these all into a requirements.txt file using the command:

```bash
$ pip freeze > requirements.txt
```

 

# **Hello World in Flask**

If you check the [official documentation](https://flask.palletsprojects.com/en/2.0.x/quickstart/) of Flask, you'll find a [minimal application](https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application) there. But as discussed above, we're not going to follow that. But we are going to write an application that is more extensible and has a good base structure for even larger applications. So, let's dive in.

Our application will exist within a package called core. To convert a usual directory to Python package, we just need to include `a __init__.py` file. So, let's create our core package first.

```bash
$ mkdir core
```

After that, let's create the ` __init__.py` file inside the core directory:

```bash
$ cd core
$ touch __init__.py
$ cd ..
```

Now that the required file has been created, we can add the following content there:

```python
from flask import Flask

app = Flask(__name__)
```

In the above Python script, we are first importing the Flask class from the flask module that we have installed. Next, we're creating an object `app` of class Flask. We use the ` __name__ ` argument to indicate the app's module or package, so that Flask knows where to find other files such as templates. 

Next, we need to create a `routes.py` file. But what goes inside that file? Inside the routes.py file, we add various routes for our application. The routes are the different URLs that the application implements. These routes are handled by Python functions called view functions. Each view function is mapped with a route using [Python decorators](https://www.geeksforgeeks.org/decorators-in-python/). So, within the core package, create a `routes.py` file and add the following content inside that:

```python
from core import app

@app.route('/')
def say_hello():
    return "Hello World!"

```

In the above script, we first imported the app object from the core package. Further, we're creating a Python function called `say_hello()` which just returns a string "Hello World!". This function, or view function, is mapped with a URL "/" using @app.route decorator. It means, whenever someone visits the "/" route, `say_hello()` method is responsible to handle the request.

Now that we have a route created, let's import it in the `a __init__.py` file as:

```python
from flask import Flask

app = Flask( __name__ )

from core import routes # Add this line
```

In the above script, we just imported the routes from core package. The thing that needs to be noticed is, we did this at the bottom of the file and not at the top. This is done just to avoid a common problem of [circular imports](https://stackabuse.com/python-circular-imports/) in Python.

Now, we have done most of the things. We just need a top-level Python script to run the application. So, outside the core package, create a `main.py` file and add the following content:

```python
from core import app

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

```

In the above script, we first imported the app object from the core package. Then inside the Python [main method](https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html), we are running the app using the run method.  By enabling debug mode using `debug=True`, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.

<u><strong>Warning</strong></u>: The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.

 Now, we are ready to run our first application in Flask. And, we can run the server just as we run a Python file using the `python main.py` command:

```python
$ python main.py 
 * Serving Flask app 'core' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 131-151-153
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
```

Once, you run the server, you'll get the above output. You'll find a URL in the last line. If you open that in your browser, you will be welcomed with a Hello World! message.

![](https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/10/12/screenshot-2021-10-12-204657_kz105t)

Hurray! We just created our first application.  
 

# **Directory and File Structure**

To build a web application, we need more than just routes. We need HTML files, static files such as CSS files, Javascript files and images, database models, and other configurations. 

1. `config.py` file : This file lies outside the core package and contains various configurations such as DEBUG, or database details such as URI.
2. `core/models.py` : This is where the models are defined. A model is a representation of a database table in code.
3. `/core/templates` : This is the directory where all HTML files will go.
4. `/core/static`: This is where static files such as CSS and JavaScript files as well as images usually go.

 

# **Configurations**

In the `config.py` file, let's add the following content.

```python
class Config(object):
    SECRET_KEY = 'guess-me'
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True

class ProductionConfig(Config):
    DEBUG = False
    MAIL_DEBUG = False

class StagingConfig(Config):
    DEVELOPMENT = True
    DEBUG = True

class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True

class TestingConfig(Config):
    TESTING = True

```

In the above script, we have created a Config class and defined various attributes inside that. Also, we have created different child classes(as per different stages of development) that inherit the Config class. Now, we can use these configurations in the `a __init__.py` file as:

```python
from flask import Flask
from config import DevelopmentConfig # Add this line

app = Flask( __name__ )
app.config.from_object(DevelopmentConfig) # Add this line

from core import routes

```

 

# **Conclusion**

So far, we have created a simple Hello World application. Also, we saw how various files are organized to form a good base structure. In the next blog, we'll create a News Application and make use of the static and templates directory there. Till then, stay tuned!