Flask CRUD Application – Create, Retrieve, Update, and Delete

Flask Crud

In this tutorial, we will learn about CRUD and then create our Flask CRUD Application. So let’s get started !!

What is a CRUD application?

A web application that deals with Create/Retrieve/Update or Delete operations is known as a CRUD application. A typical example of a CRUD application is a Blog Website.

Here,

  1. We can create a new Blog: Create
  2. See the posted blogs: Retrieve
  3. Update a Blog: Update
  4. Delete a Blog: Delete

The definitions of CRUD are summarized below:

OperationFunction
CreateCreate and add new data into the Database
RetrieveRetrieve data from the Database
UpdateUpdate existing data into the Database
DeleteDelete an existing data into the Database
Flask CRUD
CRUD

Creating a Flask CRUD Application

We will create a simple Flask CRUD application that can Create / Retrieve / Update / Delete Employee Information.

Therefore in this application, you can:

  1. Create a new Employee Information
  2. See the list of Employees.
  3. See information of a specific Employee.
  4. Update the Information of an Employee
  5. Delete an Employee information

1. Coding the Models.py

Here, we will use Flask_SQLAlchemy and SQLite DB.

First install Flask_SQLAlchemy

pip install flask_sqlalchemy

Now create a models.py file and add the following code:

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}"

Here we are just creating the EmployeeModel. Do check out the SQLAlchemy tutorial if you have any difficulty understanding the syntax

2. Coding the main Application

Now, lets code our main Flask Application File. We’ll begin by importing Flask, initialize the flask app, and set up the application runtime details.

from flask import Flask

app = Flask(__name__)

app.run(host='localhost', port=5000)

Now we need to link SQLite DB with SQLAlchemy. So add 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)

Replace <db_name> with the name you want for your DB File.

Also, we need to link the db instance (from models.py) and create DB file before the user accesses the server. So for that:

from flask import Flask

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)

Okay, now that the DB and models are in place, lets code our CRUD views.

3. Coding the Create view

The Create view should be able to do the following:

  • When the Client goes to this page (GET method), it should display a Form to get the Client’s Data.
  • On Submission (POST method), it should save the Client’s data in the EmployeeModel Database.

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

4. Coding the Retrieve views

Here we will have 2 views:

  • To display the list of Employees.
  • To display the information of a single Employee.

So the First RetrieveDataList view will be:

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

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

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

Do check out our Flask Template to know more about the template language.

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

5. Coding the Update View

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

Hence the Update View will be:

@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)

The user will submit the new details via the Form. Here we first delete the old information present in the DB and then add the new information

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>

6. Coding the Delete View

The Delete View will just 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-confirms 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.

Full code for the 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)

Implementation of the Flask CRUD Application

Run the Server and go to “/data/create

Create
Create

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

Data List
Data List

Let’s check the First one. Go to “/data/1

Data
Data

Now lets go to “/data/1/update” and update some details

Update
Update

The details are now updated. Let us now delete this Employee. Go to “/data/1/delete

Delete
Delete

Hit Yes and Voila! The Employee is Deleted

Conclusion

That’s it, guys !! This was all about CRUD Operations in Flask. Do check out our Flask REST API tutorial which is the CRUD Application in Flask REST Framework.

See you in the next article !!