34
Python for web development: Flask basic skills.
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.
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.
The vast library support makes python applicable in very many fields. A few examples of its application are:
You can read more on the applications here.
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.
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.Advantages of flask
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.
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
Flask
classMySQL
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
After successful installation, import the modules as follows:
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
You can refer to pep8 on the coding conventions used in naming the variables.
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...
don't save it as flask.py as it would conflict with Flask
This step should be familiar if you have a back-end experience.
The four basic database connection configs are:
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 on how to separate the configurations in a different file
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)
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}'
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>
Running the application
We can run the application using the
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
(app.py should be the name of your script)
This tell the terminal to use app.py with flask.
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
CMD:
set FLASK_APP=app
flask run
Powershell:
$env:FLASK_APP = "app"
flask run
The forms' action is set to
If a user tries submitting using any other method the function returns an error message-
/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.
34