CRUD Application With FLASK

NUR ARIF
5 min readJul 2, 2023
https://id.wikipedia.org/wiki/Flask

When the app starts, backEnd.py creates a Flask instance and configures an SQLite database. Then, the Product model will be defined using SQLAlchemy to represent the products table in the database. In the backend.py file you will find functions for managing data, such as create, read, update, and delete (CRUD). Basically, this file acts as a bridge between the front-end (view) and the database.

index.html is the main page of the web application. This is the initial view that will be seen by users when they access the application. Here, you can display product lists or other data that you manage. Also, there is usually a link or button to direct the user to another page, such as a new product creation page or an existing product editing page.

It is an explanation of the logical flow of program code

backEnd.py

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__) # Membuat instance
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///products.db" # KONFIGURASI DATABASE
db = SQLAlchemy(app) # Membuat Object SQLAlchmy

# Membuat model product
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
price = db.Column(db.Float, nullable=False)

# Membuat route untuk menangani GET & POST

@app.route("/", methods = ["GET", "POST"])
def handle_request():
if request.method == "POST":
name = request.form["name"]
price = request.form["price"]
new_product = Product(name=name, price=price)
db.session.add(new_product)
db.session.commit()
return redirect("/")
else:
products = Product.query.all()
return render_template('index.html', products=products)

# Route edit product
@app.route("/edit/<int:id>", methods=["GET", "POST"])
def edit_product(id):
product = Product.query.get(id)
if request.method == "POST":
product.name = request.form["name"]
product.price = request.form["price"]
db.session.commit()
return redirect("/")
else:
return render_template("edit.html", product=product)

# Route delete product
@app.route("/delete/<int:id>", methods=["POST"])
def delete_product(id):
product = Product.query.get(id)
db.session.delete(product)
db.session.commit()
return redirect("/")

#Menampilkan semua product

@app.route("/all")
def show_all_products():
with app.app_context():
products=Product.query.all()
return render_template("all_products.html", products=products)

if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(debug=True)
  1. First, we import some of the necessary modules, such as Flask and SQLAlchemy.
  2. Then, we instantiate Flask by using Flask(__name__).
  3. The SQLite database configuration is specified with app.config[“SQLALCHEMY_DATABASE_URI”].
  4. SQLAlchemy objects are created using SQLAlchemy(app).
  5. Next, we define the Product model as a class that represents the tables in the database. This model has columns such as id, name, and price.
  6. The handle_request function is the main route that handles HTTP requests with the GET and POST methods on the root (“/”) endpoint. If the method is POST, then new product data is fetched from the form, then a new Product object is created and added to the database session. After that, the changes are saved using db.session.commit() and the user will be redirected back to the main page (“/”) by using return redirect(“/”). If the method is GET, then a list of all products will be retrieved from the database using Product.query.all(), then the page “index.html” will be rendered using render_template, and a list of products will be passed as arguments.
  7. The edit_product function is a route for editing existing products. It accepts an id parameter to identify the product to change. If the method is POST, the product name and price changes are retrieved from the form, and the associated Product object is updated with those changes. Then, changes are saved using db.session.commit() and the user is redirected back to the main (“/”) page. If the method is GET, the “edit.html” page will be rendered using render_template, and the Product object corresponding to the ID will be passed as an argument.
  8. The delete_product function is a route to delete products. It accepts an id parameter to identify the product to be removed. Products with matching IDs are removed from the database using db.session.delete(), and changes are saved using db.session.commit(). Users will be redirected back to the main page (“/”) after deletion.
  9. The show_all_products function is a route to display all existing products. It fetches all the products from the database using Product.query.all(), then the page “all_products.html” is rendered using render_template, and a list of products is passed in as an argument.
  10. Finally, if the script is run directly (not imported as a module), then db.create_all() is used to create a table in the database if it doesn’t already exist. Flask apps run with app.run(debug=True).

The code starts by importing the required modules. Flask is used to create web applications, render_template to render HTML templates, request to access HTTP request data, redirect to redirect requests, and SQLAlchemy to interact with databases. Next, the Flask application instance is created with Flask(__name__). The database configuration is specified with app.config[“SQLALCHEMY_DATABASE_URI”] which specifies the URL or path of the SQLite database to use. SQLAlchemy objects are created using db = SQLAlchemy(app). The Product model is created as a class that inherits from the db.Model class from SQLAlchemy. This model has three attributes, namely id, name, and price. id is the primary key, name is the product name, and price is the product price.

Next, there is the main route / which is handled by the handle_request() function. When the method request is a POST, the data from the form (product name and price) is fetched, a new Product object is created with those values, and added to the database session. After that, the changes are confirmed and the user is redirected back to the main page (return redirect(“/”)). If the method request is GET, all products are retrieved from the database using Product.query.all(), and then the index.html page is rendered with the list of products supplied as arguments.

There is also a route /edit/<int:id> which is used to edit products with specific IDs. When a method request is a POST, the product with the matching ID is fetched from the database, and the new name and price values are stored into the product object. The change is then confirmed and the user is redirected back to the main page (return redirect(“/”)). If the method request is GET, the edit.html page is rendered with the appropriate product as an argument.

There is also a route /delete/<int:id> which is used to delete products with a certain ID. When a method request is a POST, the product with the matching ID is removed from the database, and the changes are confirmed. The user is redirected back to the main page (return redirect(“/”)).

There is also a route /all which is used to display all products. Inside this route, all products are fetched from the database using Product.query.all() and the page all_products.html is rendered with a list of products as arguments.

Inside the if __name__ == “__main__”: block, the Flask application is run with app.run(debug=True). Also, in the app context, the database is created with db.create_all() to ensure the products table is in the database before running the app.

You can check the full code here

--

--

NUR ARIF

Backend | Data Scraping | Content Writer | Python Programming | Passionate Cyber Security