CRUD Operations with Flask

CRUD Operations in Flask Web App Development

Flask is a popular Python web framework used for building web applications. CRUD activities, which stand for Create, Read, Update, and Delete, are one of the most frequent jobs while designing online applications. We will discuss how to build CRUD operations in Flask in this blog article.

Let’s explore the four CRUD operations now:

  1. Create:   To add new data to a database, utilise the create operation. In Flask, you can achieve this by utilising a form to gather user data and then save it to the database. SQLite, MySQL, and PostgreSQL are among the database systems that Flask supports.
  2. Read:  Read  Data from the database is retrieved using the read procedure. This is possible in Flask by doing a database query using SQL or an ORM (Object-Relational Mapping) tool like SQLAlchemy. The user can then see the retrieved data in a variety of forms, such as HTML or JSON.
  3. Update : The database’s existing data can be changed using the update method. This may be done in Flask by utilising an ORM tool or SQL to update the data. This can also be done through a form where the user enters the new data to be updated, similar to the create operation.
  4. Delete:   To remove data from the database, perform the delete procedure. This can be done in Flask by removing the data with an ORM tool or by using SQL. Normally, before the user’s data is really deleted, a confirmation question is presented to them.
  • An instruction manual for building a Flask CRUD application that can add, remove, update, and retrieve employee data is provided below.
  • Install Flask SQLAlchemy if you want to utilise SQLAlchemy with Flask. Run the following command in your terminal to accomplish this:
				
					pip install flask_sqlalchemy
				
			
  • This will set up the SQLAlchemy support for the Flask extension. You can import the extension into your Flask application to use SQLAlchemy after installing it.
  • You can create a file called models.py and import the required modules to build the models for your Flask application in this manner. Here’s an example:
				
					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}"
				
			
  • This code creates an EmployeeModel class with four fields: id, employee id, name, age, and position, and derives from db.Model. Each employee is identified by their unique employee id field. The object is initialised with the supplied data using the __init__ method. The name and employee ID are included in the string representation of the object that is returned by the __repr__ method.
				
					from flask import Flask
 
app = Flask(__name__)
 
app.run(host='localhost', port=5000)

				
			
  • Let’s begin by writing the primary Flask application file. We’ll start by importing Flask, starting the flask app, then configuring the runtime settings for the application.
  • First, the Flask module is imported, and a Flask application instance is created with Flask(__name__). This creates a Flask web application with the name of the module as the argument.
				
					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)

				
			
  • Next, the app.config dictionary is used to set the configuration options for the Flask application. In this case, SQLALCHEMY_DATABASE_URI is set to the URI for a SQLite database file with the specified name (<db_name>.db).
  • SQLALCHEMY_TRACK_MODIFICATIONS option is set to False to disable the Flask-SQLAlchemy modification tracking system.
  • Finally, the app.run() method is called to run the Flask application on the local machine at port 5000 with the specified database configuration.
				
					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)
				
			
  • Create View : The create view is responsible for rendering the form to add a new employee and handling the submission of the form to store the employee data to the database. Here’s an illustration of how to do this with Flask
				
					@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')
				
			
  • Let’s develop a page that contains an HTML form, createpage.html: 

				
					<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>
				
			
  • Retrieve views: To display a list of all employees or an individual employee’s data, you can define two distinct routes in Retrieve views.To demonstrate how to use these views in Flask, consider the following example:
				
					@app.route('/data')
def RetrieveDataList():
    employees = EmployeeModel.query.all()
    return render_template('datalist.html',employees = employees)

				
			
  • To display the list of employees in the list_employees.html template, you can use the following code:

				
					{% for employee in employees %}
<h3>{{employee}}</h3><hr>
{% endfor %}
				
			
  • The next 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() obtains the first employee with an employee id that matches the value of id. It returns None if such an employee doesn’t exist. The first() function returns the first result that matches the criteria after the filter by() method filters the query based on the supplied criteria.

  • We will now display the employee’s details in data.html.

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

				
			
  • Update View:  The employee ID has been included as a parameter to the URL of an update route that we have constructed. The GET method of this route presents the employee information in an HTML form that enables the user to change the employee information.

				
					@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 use the Form to provide the updated information. Here, we first remove the old data from the DB before adding the new data.

  • The form for submitting new information is displayed in the update.html file:

				
					<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>
				
			
  • Delete View : In the delete view, we do a database query to see if an employee with the specified ID already exists. If it does, we use the db.session.delete() method to remove the employee from the database and the db.session.commit method to commit the changes ().

				
					@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 template, which includes a form with a confirmation message requesting the user to confirm the deletion, is returned if the request type is not POST. The user is then redirected to the list of employees after the form has been submitted, which causes the employee to be removed from the database.

  • A confirmation message and a form to confirm the deletion will be displayed by the delete.html template:

				
					<form action='' method="post">
    Click YES to confirm
    <input type = "submit" value="YES">
    <a href='/data'>Cancel</a>
</form>
				
			

Complete CRUD application code: 

  • 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)
				
			
  • Let’s see output :  Go to “/data/create” after starting the server.

form
  • Enter the information now, then click Send. In the same way, we’ve added a couple more. Enter “/data”
data
  • Let’s examine the first. Visit “/data/1.”
data1
  • Let’s now change a few details in “/data/1/update.”

update
  • The information has been revised. Let’s eliminate this employee now. Access “/data/1/delete

delete
  • And there you have it! The worker is eliminated.
  • The implementation of CRUD operations in Flask is a vital part of creating web applications, to sum up. For a web application to be useful and user-friendly, it must be able to create, read, update, and delete data. We can quickly implement CRUD operations using Flask and build robust web applications that satisfy the demands of our consumers.
Tech Amplifier Final Logo