flask+sqlalchemy查改删


效果:

main.py

1# coding: utf-8
from sqlalchemy import CheckConstraint, Column, Integer, Text, or_
from sqlalchemy.schema import FetchedValue
from flask_sqlalchemy import SQLAlchemy
from flask import Flask,url_for,redirect,render_template,request,flash,current_app
import os,sys

app =  Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

class Teacher(db.Model):
    __tablename__ = 'Teachers'
    Id = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.Text)
    Age = db.Column(db.Integer)
    Country = db.Column(db.Text)

    def __init__(self,Name,Age,Country):
        self.Name = Name
        self.Age = Age
        self.Country = Country
@app.route('/', methods=['GET'])
def home():
    article = Teacher.query.all()
    return render_template('show_article.html',article=article)    
@app.route('/search')
def search():
    keyword = request.args.get('keyword')
    print(keyword)
    result = Teacher.query.filter(or_(Teacher.Name==keyword,Teacher.Age==keyword,Teacher.Country==keyword)).all() 
    if result:
        return render_template('show_article.html', article=result)
    else:
        return 'No content was found!'
@app.route('/list/update/',methods=['GET','POST'])
def modi(id):
    if request.method=='GET':
        result = Teacher.query.filter_by(Id=id).first_or_404()
        return render_template('update_article.html',article=result)
    else:
        Name = request.form['Name']
        Age = request.form['Age']
        Country = request.form['Country']    
        result =  Teacher.query.filter_by(Id=id).update({'Name':Name, 'Age':Age,'Country':Country})
        db.session.commit()
        return redirect('/')
@app.route('/',methods=['GET','DELETE'])        
def remove_record(id):
    if request.method=='GET':
        result = Teacher.query.filter_by(Id=id).first.or_404
        return render_template('show_article.html', article=result)
    else:
        result = Teacher.query.filter_by(Id=id).delete()
        db.session.commit()
        return  '',204
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')        
if __name__ =='__main__':
    app.run(port=8081)      

show_article.html











                 
        {% if article %}
            {% for article in article%}
            
            {% endfor %}
    
        {% else %}
            

No content was found!

{% endif %}
Name Age Country
{{article.Name}} {{article.Age}} {{article.Country}} 修改 删除

update_article.html