DEV Community

Cover image for Python for web development: Flask basic skills.
Martin N Thuo
Martin N Thuo

Posted on • Updated on

Python for web development: Flask basic skills.

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.

Python for Web Development

Python is widely used for web development today. It has very rich frameworks like Django, Flask,Pyramid and Bottle 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 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.

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:

python3 -m pip install flask

python3 -m pip install flask_mysqldb
Enter fullscreen mode Exit fullscreen mode

After successful installation, import the modules as follows:

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

Enter fullscreen mode Exit fullscreen mode

Create an instance of Flask class

You can refer to pep8 on the coding conventions used in naming the variables.

app = Flask(__name__)

Enter fullscreen mode Exit fullscreen mode

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...

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
  2. The user
  3. The user password
  4. The name of the database.
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'MyDB'
Enter fullscreen mode Exit fullscreen mode

You need to replace the configurations with yours where necessary.

Refer here 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 😊.

mysql = MySQL(app)
Enter fullscreen mode Exit fullscreen mode

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.

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

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

@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}'
Enter fullscreen mode Exit fullscreen mode

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

<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>
Enter fullscreen mode Exit fullscreen mode

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:

export FLASK_APP=app.py

flask run

Enter fullscreen mode Exit fullscreen mode

CMD:

set FLASK_APP=app

flask run
Enter fullscreen mode Exit fullscreen mode

Powershell:

$env:FLASK_APP = "app"

flask run
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)