how to delete items from database using a flask framework?

  • Last Update :
  • Techknowledgy :

If you are going to use a POST request the variable will be available under flask's request.form. If you stay with DELETE I think you need to change your uri. For example:

@app.route('/delete/<int:postID>', methods=['DELETE'])

In the .py:

@app.route('/delete', methods = ['POST'])
def delete_entry():
   if not session.get('logged_in'):
   abort(401)
db = get_db()
db.execute('delete from entries where id = ?' [request.form['entry_id']])
db.commit()
flash('Entry deleted')
return redirect(url_for('show_entries'))

In the HTML:

<form action="{{ url_for('delete_entry') }}" method=post class=delete-entry>
          <input type="hidden" name="entry_id" value="{{ loop.revindex }}">
          <input type="submit" value="Delete" />
</form>

Suggestion : 2

1 day ago We create a dao.py file to write the below code. To delete single product from database table we can simply use WHERE condition but to delete multiple rows we need to use IN clause with WHERE condition. Even for single record deletion we can use IN clause with WHERE condition. import pymysql from db import mysql def products (): try: conn ... ,  › Firebaseexception failed to parse node with class in nodeutilitiesnodefromjson ,I'm working with a Flask framework, and am trying to delete an entry from the database. The code below gives this error: "The method is not allowed for the requested URL.", 4 days ago Sep 09, 2020  · Python answers related to “how to delete a record from database using flask python” delete and start fresh with db django; django flush database; delete database entry using name django; django drop database postgres; flask remove file after send_file; delete a record by id in flask sqlalchemy; django how to delete a db field; django drop ...


<form action="{{ url_for('delete_entry', id=entry.id) }}" method="POST">      <input type="hidden" name="_method" value="DELETE" />      <input type="submit" value="Delete entry" /> </form> 
1._
CREATE TABLE `product`(`id`
   int unsigned NOT NULL AUTO_INCREMENT, `name`
   varchar(255) NOT NULL, `code`
   varchar(255) NOT NULL, `price`
   double NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4;
INSERT INTO `product`(`id`, `name`, `code`, `price`) VALUES(1, 'American Tourist', 'AMTR01', 12000.00), (2, 'EXP Portable Hard Drive', 'USB02', 5000.00), (3, 'Shoes', 'SH03', 1000.00), (4, 'XP 1155 Intel Core Laptop', 'LPN4', 80000.00), (5, 'FinePix Pro2 3D Camera', '3DCAM01', 150000.00), (6, 'Simple Mobile', 'MB06', 3000.00), (7, 'Luxury Ultra thin Wrist Watch', 'WristWear03', 3000.00), (8, 'Headphone', 'HD08', 400.00);
from flask
import Flask app = Flask(__name__)
from flask import Flask  app = Flask(__name__)
from app
import app from flaskext.mysql
import MySQL mysql = MySQL() # MySQL configurations app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

Suggestion : 3

So how do we get data back out of our database? For this purpose Flask-SQLAlchemy provides a query attribute on your Model class. When you access it you will get back a new query object over all records. You can then use methods like filter() to filter the records before you fire the select with all() or first(). If you want to go by primary key you can also use get().,The session here is not the Flask session, but the Flask-SQLAlchemy one. It is essentially a beefed up version of a database transaction. This is how it works:,Alright, that was not hard. What happens at what point? Before you add the object to the session, SQLAlchemy basically does not plan on adding it to the transaction. That is good because you can still discard the changes. For example think about creating the post at a page but you only want to pass the post to the template for preview rendering instead of storing it in the database.,Now that you have declared models it’s time to query the data from the database. We will be using the model definitions from the Quickstart chapter.

>>> from yourapp
import User
   >>>
   me = User('admin', 'admin@example.com') >>>
   db.session.add(me) >>>
   db.session.commit()
>>> me.id
1
>>> db.session.delete(me) >>>
   db.session.commit()
>>> peter = User.query.filter_by(username = 'peter').first() >>>
   peter.id
2
   >>>
   peter.email
u 'peter@example.org'
>>> missing = User.query.filter_by(username = 'missing').first() >>>
   missing is None
True
>>> User.query.filter(User.email.endswith('@example.com')).all()
[<User u'admin'>, <User u'guest'>]

Suggestion : 4

Post date April 3, 2022 ,© 2022 The Web Dev

For instance, we write

session.delete(obj1)
session.delete(obj2)

session.commit()

Suggestion : 5

First, establish a connection the SQLite database by creating a Connection object using the connect() function.,The following  create_connection() function establishes a database connection to an SQLite database specified by a database file name:,Second, to execute a DELETE statement, you need to create a Cursor object using the cursor() method of the Connection object.,This main() function calls the create_connection() function and the delete_task() function to delete the task with id 2 from the tasks table:

The following  create_connection() function establishes a database connection to an SQLite database specified by a database file name:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
def create_connection(db_file):
   ""
" create a database connection to the SQLite database
specified by the db_file
   : param db_file: database file: return: Connection object or None ""
"
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
   print(e)

return connCode language: Python(python)

The following delete_task() function deletes a task in the tasks table by id.

def delete_task(conn, id):
   ""
"
Delete a task by task id
   : param conn: Connection to the SQLite database: param id: id of the task: return:
      ""
"
sql = 'DELETE FROM tasks WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id, ))
conn.commit() Code language: Python(python)

The following delete_all_tasks() function deletes all rows in the tasks table.

def delete_all_tasks(conn):
   ""
"
Delete all rows in the tasks table: param conn: Connection to the SQLite database: return:
   ""
"
sql = 'DELETE FROM tasks'
cur = conn.cursor()
cur.execute(sql)
conn.commit() Code language: Python(python)

Here is the full program:

import sqlite3
from sqlite3
import Error

def create_connection(db_file):
   ""
" create a database connection to the SQLite database
specified by the db_file
   : param db_file: database file: return: Connection object or None ""
"
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
   print(e)

return conn

def delete_task(conn, id):
   ""
"
Delete a task by task id
   : param conn: Connection to the SQLite database: param id: id of the task: return:
      ""
"
sql = 'DELETE FROM tasks WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id, ))
conn.commit()

def delete_all_tasks(conn):
   ""
"
Delete all rows in the tasks table: param conn: Connection to the SQLite database: return:
   ""
"
sql = 'DELETE FROM tasks'
cur = conn.cursor()
cur.execute(sql)
conn.commit()

def main():
   database = r "C:\sqlite\db\pythonsqlite.db"

# create a database connection
conn = create_connection(database)
with conn:
   delete_task(conn, 2);
# delete_all_tasks(conn);

if __name__ == '__main__':
   main() Code language: Python(python)