Python for web development: Flask basic skills.

Tags: python, webdev, devops, flask
Published: 2021-08-12 09:02:14

## Introduction

Python is an interpreted high-level general-purpose programming language.

It is the most preferred language of choice for most beginners because of its relatively faster learning curve.

 Python is very easy to read compared to other programming languages which has a very steep learning curve.

### Advantages of python

- Python is very easy to __read__, __learn__ and __write__.
- Its free and open source.
- It has a very large library support.
- It is very portable
- It is a dynamically typed language.

Due to its simplicity of writing and learning, it leads to high productivity. It takes significantly less time to write Python code compared to other languages.

### Application areas of Python
The vast library support makes python applicable in very many fields. A few examples of its application are:
 - web development
 - Scientific and numeric Applications
 - Artificial Intelligence and Machine Learning
 - Desktop GUI
 - Software development
 - Web Scraping Applications

 You can read more on the applications [here](https://www.upgrad.com/blog/python-applications-in-real-world/).

## Python for Web Development

Python  is widely used for web development today. It has very rich frameworks like [Django](https://www.djangoproject.com/), [Flask](https://flask.palletsprojects.com/en/2.0.x/),[Pyramid](https://trypyramid.com/) and [Bottle](https://bottlepy.org/) to assist in the job.

Flask is the most preferred for new learners. It is simple, flexible and unopinionated.
It gives you a developer varieaties of choice when developing web applications. Its main advantage is having the opportunity to build from the ground up.

We are going to explore `Flask` for in this article.

### Why Flask?

__Advantages of flask__

- Technical experimentation.
- Easy to use.
- Routing URL is easy
- It is more compatible with latest technologies.

That is to mention just few.

Flask is often compared to django which is also a Pyhton web framework. Django provides many out of the box features and reduces time to build complex applications.

You can read more on their differences of [here](https://www.guru99.com/flask-vs-django.html) to know what tool is best suited in what.

## Lets code a simple flask application.

We will create a simple apllication that takes input from a form and stores it in a database. In this case [MySQL](https://dev.mysql.com/doc/).

__The process overview: the bigger picture__

- Import the required modules.
- Create an instance of the `Flask` class
- Set database connection configurations
- Create an instance of `MySQL`
- Route the requests.

### Importing the required module

For this simple application we need `flask` from which we require the `Flask` class and `render_template`, and `MySQL` from `flask_mysqldb`.

> You need to install the `flask` modules and `flask_mysqldb` if you do not already have them.

To install the modules:

```bash
python3 -m pip install flask

python3 -m pip install flask_mysqldb
```

After successful installation, import the modules as follows:

```python
from flask import Flask, render_template, request
from flask_mysqldb import MySQL

```
### Create an instance of `Flask` class

You can refer to [pep8](https://exploreflask.com/en/latest/conventions.html) on the coding conventions used in naming the variables.

```python
app = Flask(__name__)

```
The first argument of the instance is the name of the application's module or package.

If you are using a single module, you should use `__name__` because depending on if it's started as application or imported as a module the name will be different (`__main__` vs the actual import name)

This is so that Flask knows where to look for tempelates, static files etc. [Read more...](https://flask.palletsprojects.com/en/2.0.x/quickstart/)

*don't save it as flask.py as it would conflict with Flask*

### Set the database configurations

This step should be familiar if you have a back-end experience.

The four basic database connection __configs__ are:

1. The host
1. The user
1. The user password
1. The name of the database.

```Python
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'MyDB'
```
> You need to replace the configurations with yours where necessary.

*Refer [here](https://dev.to/kubona_my/dealing-with-environment-variables-in-flask-o1) on how to separate the configurations in a different file*

### Create a `MySQL` instance

If you remember how created the `Flask` instance you can challenge your yourself.

Create a `MySQL` instance passing `app` (or the name you used).

Hope you did it... but if you didn't don't worry we will do it together 😊.

```python
mysql = MySQL(app)
```

### Routing

Up to this point it has been easy but we only set the connection. (hope it worked 😊)

We will now set routes for user to be served with different actions for different `routes`.

Routing is a very wide area of coverage and we will barely scrap the surface. You can read more on this [here](https://flask.palletsprojects.com/en/2.0.x/quickstart/#routing).

Use the `route()` decorator to bind a function to a URL.

__Decorators__ allows modifying of the behavior of a function or a class.

```python
@app.route('/')
def form():
    return render_template('form.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method != "POST":
        return "Use the sign up form"

    if request.method == 'POST':
        details = request.form
        name = details['name']
        email = details['email']
        message = details['message']
        cursor = mysql.connection.cursor()
        cursor.execute("INSERT INTO users(name, email, message) VALUES (%s, %s, %s)",(name, email, message))
        cursor.connection.commit()
        cursor.close()
        return f'Created user {name}'
```
__What did we just write ?__

The first decorator invokes the `form()` function when a user visits the root `URL`.

This will render a `form.html` page using the `render_template` method we imported from `flask`.

The file should be stored in a directory named `templates`.

You can create as many routes as you want.

__form.html__

```html
<form action="/register" method="POST">
  <p>NAME: <input type="text" name="name" /></p>
  <p>EMAIL: <input type="text" name="email" /></p>
  <p>BIO: <input type="text" name="message" /></p>

  <p><input type="submit" value="submit" /></p>
</form>
```
__Running the application__
We can run the application using the `flask run` command or using python and the -m switch command and flask: `python3 -m flask run`.

Before running the app, we first need to export `FLASK_APP=app.py`. 
(app.py should be the name of your script)
This  tell the terminal to use app.py with flask.

Bash: 

```bash
export FLASK_APP=app.py

flask run

``` 
CMD:
```cmd
set FLASK_APP=app

flask run
```

Powershell:
```powershell
$env:FLASK_APP = "app"

flask run
```

The forms' action is set to `/register` using the `POST` method.
If a user tries submitting using any other method the function returns an error message- `Use the sign up form` - to the user.

A successful save should return a statement with the name of the user saved.

This was a very simple application that should not be used in deployment. You can always read more of __flask__ from the flask [guide](https://flask.palletsprojects.com/en/2.0.x/).