Building Your First Website with Flask: Part 4
Creating forms and databases with Flask
Our team has been writing several posts recently focused on developing a website using Flask.
- Part 1 — Hello World and Beyond
- Part 2 — HTML Templates and CSS
- Part 3 — Keeping Track of Sessions and Intro to Forms
For Part 4 of this series, we’ll be covering creating a database to handle various data. After creation, a set of features available to database management in Flask gets considered as well. So for the fourth part, we plan to achieve the following from our simple website:
· Inserting data from a form
· Incorporating a database
· Handling basic user profile
Inserting Data From a Form
With Flask, form data can be sent to a template. The form data received will trigger a function that forwards the collected data to a template for rendering on selected web pages.
In the example below, we will use the home page, which can be found at the
‘/’ URL. This renders a web page (
user.html) with a form. The data filled in by a user is posted to the
‘/result’ URL. The
results() function triggers the output on the resulting URL. The function also collects form data present in
request.form using a dictionary style (dictionary object) and sends it to
result.html for rendering.
The template renders the form data dynamically into an HTML table. Below is the code for
Given below is the HTML script of
Once you submit the form, it will call the result HTML page. The code of the template (
result.html) is given below:
Run the Python script, and enter the URL http://localhost:5000/ in the browser.
The output of going to the form will look like this (minus what we typed in):
When the submit button is clicked, form data is rendered on
result.html in the form of an HTML table.
Incorporating a Database
If you recall, in our comparison of Flask vs. Django, Flask is a micro-web framework in Python. This definition implies it does not feature an object-relational mapper (ORM) (whereas Django does).
So if you wish to incorporate an interactive database, then you require the additional installation of an extension. SQLAlchemy has become a popular choice to install. In Flask, the ready-made extension for the addition SQLAlchemy is called Flask-SQLAlchemy.
The installation of Flask-SQLAlchemy requires the use of pip in your active virtual environment created for Flask. To install the extension, enter the following into your active environment for Flask in Python:
pip install flask-sqlalchemy
After the successful installation of Flask-SQLAlchemy, the next installation needed is MySQL. This installation can be achieved using:
pip install mysql
After the successful installation of Flask-SQLAlchemy alongside other dependencies, it is time to create our interactive database.
Creating a Database
The use of SQLAlchemy in creating a database is pretty straightforward. SQLAlchemy supports several approaches to working with database. A common approach is the use of declarative syntax that permits you to create classes for modeling the database.
So for our simple Flask tutorial, we would make use of SQLite to serve as the back end. Other back-end solutions, like MySQL or Postgres, could be employed. To begin, we will be looking at how to create:
· A database file through the normal SQLAlchemy
· A separate script that uses the different Flask-SQLAlchemy syntax
So let’s start by putting the code into a file called
The early part of the code may appear similar, as we are asking Python to import SQLAlchemy and other essential extensions needed to make the different parts of the code work.
Subsequently, the code tries to create SQLAlchemy’s engine object, which essentially connects Python to the selected database. Also, we connect the SQLite and create a database file in place of creating a database inside the memory.
Additionally, the base class created is meant to serve the creation of declarative-class definitions. This class definition defines the database table. For example, we might want to define a class called
user that is attached to a user table.
Also note the name given to the table is done through the
__tablename__ class attribute. The creation of the table’s columns is set using the data types we require.
You can read more about it and get in-depth details from the well-written documentation. On running the code above, an error in the output terminal is obtained. Now let’s make all this work in Flask.
Using Flask-SQLAlchemy to Create a Database
The first thing we require in using Flask-SQLAlchemy is the creation of a simple application script. Let’s call the application script
apps.py. Now let’s add the code below into the Python file and save it.
Also, a simple secret is to set up a database object at the same time, which permits the integration of SQLAlchemy into Flask.
Next is to create the Flask app object and provide a location for the SQLAlchemy database file. The creation of a
models.py file can do the trick. This would contain the following code:
Flask-SQLAlchemy does not necessitate all the imports as required by the plain SQLAlchemy. All we need is the database (db) object created in the app script. From there, we add
db to all classes using the original SQLAlchemy code.
Also, the predefined
db.Model also serves as the base class. To help initialize the database, we create the
The code above would initialize the database using the table created within the model’s script. To visualize the initialization, let’s make some additions to our
Here we only import our app object alongside the
init_db function. Now let’s run the code in the terminal, using the following:
While this code is running, you can go to the link below to see what the page looks like:
We have successfully created a simple database entry using a form as well as a web app that has an empty database.
The database created for the web app cannot accept any input yet, but it offers an introduction to the use of a database.
In the next part, we will integrate the database with the Flask front end so you can start creating new users.