fromflaskimportFlask,render_template,request,redirect,url_forimportpsycopg2app=Flask(__name__)# Connect to the databaseconn=psycopg2.connect(database="flask_db",user="postgres",password="root",host="localhost",port="5432")# create a cursorcur=conn.cursor()# if you already have any table or not id doesnt matter this# will create a products table for you.cur.execute('''CREATE TABLE IF NOT EXISTS products (id serial \ PRIMARY KEY, name varchar(100), price float);''')# Insert some data into the tablecur.execute('''INSERT INTO products (name, price) VALUES \ ('Apple', 1.99), ('Orange', 0.99), ('Banana', 0.59);''')# commit the changesconn.commit()# close the cursor and connectioncur.close()conn.close()@app.route('/')defindex():# Connect to the databaseconn=psycopg2.connect(database="flask_db",user="postgres",password="root",host="localhost",port="5432")# create a cursorcur=conn.cursor()# Select all products from the tablecur.execute('''SELECT * FROM products''')# Fetch the datadata=cur.fetchall()# close the cursor and connectioncur.close()conn.close()returnrender_template('index.html',data=data)@app.route('/create',methods=['POST'])defcreate():conn=psycopg2.connect(database="flask_db",user="postgres",password="root",host="localhost",port="5432")cur=conn.cursor()# Get the data from the formname=request.form['name']price=request.form['price']# Insert the data into the tablecur.execute('''INSERT INTO products \ (name, price) VALUES (%s, %s)''',(name,price))# commit the changesconn.commit()# close the cursor and connectioncur.close()conn.close()returnredirect(url_for('index'))@app.route('/update',methods=['POST'])defupdate():conn=psycopg2.connect(database="flask_db",user="postgres",password="root",host="localhost",port="5432")cur=conn.cursor()# Get the data from the formname=request.form['name']price=request.form['price']id=request.form['id']# Update the data in the tablecur.execute('''UPDATE products SET name=%s,\ price=%s WHERE id=%s''',(name,price,id))# commit the changesconn.commit()returnredirect(url_for('index'))@app.route('/delete',methods=['POST'])defdelete():conn=psycopg2.connect(database="flask_db",user="postgres",password="root",host="localhost",port="5432")cur=conn.cursor()# Get the data from the formid=request.form['id']# Delete the data from the tablecur.execute('''DELETE FROM products WHERE id=%s''',(id,))# commit the changesconn.commit()# close the cursor and connectioncur.close()conn.close()returnredirect(url_for('index'))if__name__=='__main__':app.run(debug=True)