Flask - 使用db.session.delete()在DB中删除记录

时间:2017-09-04 10:03:20

标签: python database sqlite flask

我的SQLite3数据库中有Students表。该表有id和name字段。

这是我的 app.py

#!/usr/bin/python

from flask import Flask, render_template, json, request, flash,session,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
import sqlite3



conn = sqlite3.connect('test.db')





app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
db = SQLAlchemy(app)









class Students(db.Model):
    id = db.Column('student_id',db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
        return '<Students %r>' % self.name


db.create_all()


@app.route("/")
def main():
    return render_template('index.html')




@app.route('/new', methods = ['GET', 'POST'])
def new():
   if request.method == 'POST':
      if not request.form['name'] or not request.form['id']:
         flash('Please enter all the fields', 'error')
      else:
         student = Students(request.form['name'], request.form['id'])
         db.session.add(student)
         db.session.commit()

         flash('Record was successfully added')
         return redirect(url_for('show_all'))
   return render_template('new.html')


@app.route('/deleted', methods = ['GET', 'POST'])
def deleted():

    if request.method == 'POST':
        if not request.form['name'] or not request.form['id']:
            flash('Please enter the right number you asshole!','error')
        else:
            student1 = Students(request.form['id'])
            Students.query.filter_by(id='student1').delete()
            db.session.commit()

            flash('Record was deleted successfully ')
            return redirect(url_for('show_all'))
    return render_template('deleted.html')




@app.route("/admin")
def show_all():
   return render_template('show_all.html', Students = Students.query.all() )

我刚刚将模板从我添加记录的地方复制到我删除记录但没有名称feild的地方,现在我只想通过ID删除记录。我从堆栈溢出的上一个问题得到了这个:

User.query.filter_by(id=123).delete()

因此,在我从ID表单中请求了值之后,我将其分配给变量students1,然后将其传递给查询以便删除它。通过它,重定向并重新引导show_all模板。

因此,做到这一点:

@app.route('/deleted', methods = ['GET', 'POST'])
def deleted():

    if request.method == 'POST':
        if not request.form['name'] or not request.form['id']:
            flash('Please enter the right number you asshole!','error')
        else:
            student1 = Students(request.form['id'])
            Students.query.filter_by(id='student1').delete()
            db.session.commit()

            flash('Record was deleted successfully ')
            return redirect(url_for('show_all'))
    return render_template('deleted.html')

但我一直收到400 Bad Request错误。任何帮助表示赞赏。我刚刚开始学习数据库。

这是HTML:

deleted.html

<!DOCTYPE html>
<html>
   <body>

      <h3>SCS EC Attendance Kickout the student</h3>
      <hr/>

      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {{ message }}
         </div>
      {%- endfor %}

      <form action = "{{ request.path }}" method = "post">
         <label for = "id">Id Number</label><br>
         <input type = "text" name = "id" placeholder = "Student Id" /><br>
         <input type = "submit" value = "Delete this motherfucker!" />

      </form>

   </body>
</html>

show_all.html

<!DOCTYPE html>
<html lang = "en">
   <head>
      <link rel="stylesheet" type="text/css" href="table.css">
   </head>
   <body>

      <h3>
         <a href = "{{ url_for('show_all') }}">SCS EC Attendance System</a>
      </h3>

      <hr/>
      {%- for message in get_flashed_messages() %}
         {{ message }}
      {%- endfor %}

      <h3>Students (<a href = "{{ url_for('new') }}">Add Student
         </a>)</h3>

      <h3>Students (<a href = "{{ url_for('deleted') }}">Massacre Student
         </a>)</h3>



   <table class="responstable">
   <thead>

   <tr>
    <th>Name</th>
    <th>Id</th>
  </tr>
  </thead>


         <tbody>
            {% for Student in Students %}
               <tr>
                  <td>{{ Student.name }}</td>
                  <td>{{ Student.id }}</td>

            {% endfor %}
         </tbody>
      </table>
                  <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="new" role="button">Sign up today</a>
                <a class="btn btn-lg btn-success" href="show_all" role="button">Administrate</a>
            </p>

   </body>
</html>

1 个答案:

答案 0 :(得分:0)

我不太确定这会删除你的记录。

Students.query.filter_by(id='student1').delete()

尝试

的标准方式
x = Students.query.filter_by(id='student1')
db.session.delete(x)
db.session.commit()

试试并评论您的回复。