Flask CRUD Application


CRUD stands for Create, Retrieve, Update, and Delete. You will learn to create your own Flask CRUD application and also, learn about CRUD in this tutorial. Hop on, let's enjoy the ride!

What are CRUD applications? Its a web application that does create/retrieve/update or deletes operations. A blog site is a perfect example of a CRUD application.

  • You can create a Blog (Create)
  • See posted blogs (Retrieve)
  • Update blogs (Update)
  • Delete blogs (Delete)

Related course: Create Web Apps with Python Flask

Creating a Flask CRUD application

In this section, we will create an uncomplicated Flask CRUD application we can use to create/retrieve/ update/ employee info. Thus in this application, you tend to:

Action Database action
Create Generate and add new data to a database
Retrieve Recovers data from a database
Update Update existing data to a database
Delete Delete existing data from a database

Models.py coding

In this model, we use Flask_SQLAlchemy and SQLite DB.

First of all, we install the SQLAlchemy

pip install flask_sqlalchemy

then create a models.py file, and then add these codes:

from flask_sqlalchemy import SQLAlchemy
 
db = SQLAlchemy()
 
class EmployeeModel(db.Model):
    __tablename__ = "table"
 
    id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.Integer(),unique = True)
    name = db.Column(db.String())
    age = db.Column(db.Integer())
    position = db.Column(db.String(80))
 
    def __init__(self, employee_id,name,age,position):
        self.employee_id = employee_id
        self.name = name
        self.age = age
        self.position = position
 
    def __repr__(self):
        return f"{self.name}:{self.employee_id}"

In this patch, we are simply creating the EmployeeModel. If you find it a bit difficult to understand the syntax, check out our tutorials on SQLAlchemy.

You can easily Deploy a Flask app online

The main Application Coding

It's time to code the file for the main Flask application. We kick off by importing Flask, initializing the flask application; and fix up a runtime for the application.

from flask import Flask
 
app = Flask(__name__)
 
app.run(host='localhost', port=5000)

Next, we link the SQLAlchemy with SQLite. In doing that, include the following code snippet:

from flask import Flask
 
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
 
app.run(host='localhost', port=5000)

Exchange with the name you want for your DB File. We also need to connect the DB instance (from models.py) and create a DB file before the user accesses the server. So:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
app =Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
 
@app.before_first_request
def create_table():
    db.create_all()
 
app.run(host='localhost', port=5000)

Flask Create database file

Considering the DB and models are in place, its time to code our CRUD views.

Create view Coding

The following should be able to be done by the create view: When a user visits this page (GET method), it should display a form to get the user's details. During submission (POST method), it should save the user data in the EmployeeModel Database.
The create view will be:

@app.route('/data/create' , methods = ['GET','POST'])
def create():
    if request.method == 'GET':
        return render_template('createpage.html')
 
    if request.method == 'POST':
        employee_id = request.form['employee_id']
        name = request.form['name']
        age = request.form['age']
        position = request.form['position']
        employee = EmployeeModel(employee_id=employee_id, name=name, age=age, position = position)
        db.session.add(employee)
        db.session.commit()
        return redirect('/data')

The createpage.html will contain the HTML Form:

<form action='' method = "POST">
  <p>employee ID <input type = "integer" name = "employee_id" /></p>
  <p>name <input type = "text" name = "name" /></p>
  <p>age <input type = "integer" name = "age" /></p>
  <p>position <input type = "text" name = "position" /></p>
  <p><input type = "submit" value = "Submit" /></p>
</form>

create page template

  1. Retrieve views Coding Here we have two views:

To display the Employees list, a single Employee information.

The First RetrieveDataList view will be:

@app.route('/data')
def RetrieveDataList():
    employees = EmployeeModel.query.all()
    return render_template('datalist.html',employees = employ

The datalist.html file will display the list of Employees:

{% for employee in employees %}
<h3>{{employee}}</h3><hr>
{% endfor %}

to know more on template language, visit our Flask Template.

The Second RetrieveSingleEmployee View will be:

@app.route('/data/<int:id>')
def RetrieveSingleEmployee(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if employee:
        return render_template('data.html', employee = employee)
    return f"Employee with id ={id} Doenst exist"

EmployeeModel.query.filter_by(employee_id = id).first() will return the first Employee with Employee ID = id in the DB or return None if the Employee with that id does not exist. The data.html displays the information of the Employee:

<h3>Id</h3>
<p>{{employee.employee_id}}</p><hr>
<h3>Name</h3>
<p>{{employee.name}}</p><hr>
<h3>Age</h3>
<p>{{employee.age}}</p><hr>
<h3>Position</h3>
<p>{{employee.position}}</p><hr>

Related course: Create Web Apps with Python Flask

CRUD Update View

The Update View will update the Employee details in the DB with the new one submitted by the user.

@app.route('/data/<int:id>/update',methods = ['GET','POST'])
def update(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if request.method == 'POST':
        if employee:
            db.session.delete(employee)
            db.session.commit()
 
            name = request.form['name']
            age = request.form['age']
            position = request.form['position']
            employee = EmployeeModel(employee_id=id, name=name, age=age, position = position)

            db.session.add(employee)
            db.session.commit()
            return redirect(f'/data/{id}')
        return f"Employee with id = {id} Does nit exist"
 
   return render_template('update.html', employee = employee

Therefore the Update View will be:

The user will submit the new details through the Form. First we delete the old information present in the DB and then include the new one

The update.html displays the Form for the submission of new details:

<form action='' method = "POST">
  <p>name <input type = "text" name = "name" value="{{employee.name}}"/></p>
  <p>age <input type = "integer" name = "age"  value="{{employee.age}}"/></p>
  <p>position <input type = "text" name = "position" value="{{employee.position}}"/></p>
  <p><input type = "submit" value = "Submit" /></p>
</form>

CRUD Delete View

The Delete View will delete the Employee Information from the DB File. The Delete View will be:

@app.route('/data/<int:id>/delete', methods=['GET','POST'])
def delete(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if request.method == 'POST':
        if employee:
            db.session.delete(employee)
            db.session.commit()
            return redirect('/data')
        abort(404)
 
    return render_template('delete.html')
The delete.html just re-asserts the deletion:
<form action='' method="post">
    Click YES to confirm
    <input type = "submit" value="YES">
    <a href='/data'>Cancel</a>
</form>

If the user presses Yes then the Employee is deleted. Or else he is taken back.

Btw, you can easily Deploy your Flask app online

Full code for CRUD application

The models.py:

from flask_sqlalchemy import SQLAlchemy
 
db =SQLAlchemy()
 
class EmployeeModel(db.Model):
    __tablename__ = "table"
 
    id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.Integer(),unique = True)
    name = db.Column(db.String())
    age = db.Column(db.Integer())
    position = db.Column(db.String(80))
 
    def __init__(self, employee_id,name,age,position):
        self.employee_id = employee_id
        self.name = name
        self.age = age
        self.position = position
 
    def __repr__(self):
        return f"{self.name}:{self.employee_id}"

The main flask application:

from flask import Flask,render_template,request,redirect
from models import db,EmployeeModel
 
app = Flask(__name__)
 
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
 
@app.before_first_request
def create_table():
    db.create_all()
 
@app.route('/data/create' , methods = ['GET','POST'])
def create():
    if request.method == 'GET':
        return render_template('createpage.html')
 
    if request.method == 'POST':
        employee_id = request.form['employee_id']
        name = request.form['name']
        age = request.form['age']
        position = request.form['position']
        employee = EmployeeModel(employee_id=employee_id, name=name, age=age, position = position)
        db.session.add(employee)
        db.session.commit()
        return redirect('/data')
 
 
@app.route('/data')
def RetrieveList():
    employees = EmployeeModel.query.all()
    return render_template('datalist.html',employees = employees)
 
 
@app.route('/data/<int:id>')
def RetrieveEmployee(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if employee:
        return render_template('data.html', employee = employee)
    return f"Employee with id ={id} Doenst exist"
 
 
@app.route('/data/<int:id>/update',methods = ['GET','POST'])
def update(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if request.method == 'POST':
        if employee:
            db.session.delete(employee)
            db.session.commit()
            name = request.form['name']
            age = request.form['age']
            position = request.form['position']
            employee = EmployeeModel(employee_id=id, name=name, age=age, position = position)
            db.session.add(employee)
            db.session.commit()
            return redirect(f'/data/{id}')
        return f"Employee with id = {id} Does nit exist"
 
    return render_template('update.html', employee = employee)
 
 
@app.route('/data/<int:id>/delete', methods=['GET','POST'])
def delete(id):
    employee = EmployeeModel.query.filter_by(employee_id=id).first()
    if request.method == 'POST':
        if employee:
            db.session.delete(employee)
            db.session.commit()
            return redirect('/data')
        abort(404)
 
    return render_template('delete.html')
 
app.run(host='localhost', port=5000)

Implementing the Flask CRUD application

Demo

Launch the Server and go to /data/create

List Next, enter the details and press Submit. Similarly, I have added a few more. Go to /data

Read Lets check the First one. Go to /data/1

Update Next lets go to /data/1/update and update some details

Delete The details are now updated. Let us now delete this Employee. Go to /data/1/delete Hit Yes and Bang! The Employee is Deleted

Final remarks:

Done!

There you go, that is all you have about CRUD operations in Flask. For the CRUD application in Flask, do visit our Flask REST API tutorial.

Related course: Create Web Apps with Python Flask