Flask之图书馆数据库增删改-简单案列

1、flask代码包括数据库配置,数据库模型类,CSRF,数据库增删改查

from flask import Flask, render_template, request, redirect, flash
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)

# 配置数据库信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/mydatabase'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config['SECRET_KEY'] = 'aadsadsdsdaad'
# 使用CSRF保护app
CSRFProtect(app)

app.app_context().push()
# 创建sqlalchemy对象,关联app
db = SQLAlchemy(app)

class Author(db.Model):
    __tablename__ = 'authors'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))

    #建立关系属性
    books = db.relationship("Book", backref='author')

class Book(db.Model):
    __tablename__ = 'books'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))

    # 建立外键
    author_id = db.Column(db.Integer, db.ForeignKey(Author.id))

@app.route('/')
def index():
    #查询所有信息
    authors = Author.query.all()
    return render_template('library.html', authors=authors)

@app.route('/add_data', methods=["POST", "GET"])
def add_data():
    author_name = request.form.get('author')
    book_name = request.form.get('book')
    if not all([author_name,book_name]):
        flash("作者或者书籍不能为空")
    # 查询数据库中是否有该作者
    author = Author.query.filter(Author.name == author_name).first()
    # 若是有该作者,则查询是否有写过该书
    if author:
        book = Book.query.filter(Book.name == book_name,Book.author_id==author.id).first()
        if book:
            flash("该作者,已经有该书了")
        else:
            book = Book(name=book_name,author_id=author.id)
            db.session.add(book)
            db.session.commit()
    else:
        author = Author(name=author_name)
        db.session.add(author)
        db.session.commit()

        book = Book(name=book_name, author_id=author.id)
        db.session.add(book)
        db.session.commit()

    return redirect('/')

#删除书籍
@app.route('/delete_data/')
def delete_book(book_id):
    book = Book.query.get(book_id)
    db.session.delete(book)
    db.session.commit()

    return redirect('/')

#删除作者
@app.route('/delete_author/')
def delete_author(author_id):
    author = Author.query.get(author_id)
    for book in author.books:
        db.session.delete(book)
    db.session.delete(author)
    db.session.commit()

    return redirect('/')

if __name__ == "__main__":
    db.drop_all()
    db.create_all()

    au1 = Author(name='豆豆')
    au2 = Author(name='古龙')
    au3 = Author(name='天蚕')
    db.session.add_all([au1, au2, au3])
    db.session.commit()

    bk1 = Book(name='豆豆三部曲', author_id=au1.id)
    bk2 = Book(name='遥远的救世主', author_id=au1.id)
    bk3 = Book(name='天龙八部', author_id=au2.id)
    bk4 = Book(name='大主宰', author_id=au3.id)
    bk5 = Book(name='斗气大陆', author_id=au3.id)
    db.session.add_all([bk1,bk2,bk3,bk4,bk5])
    db.session.commit()

    app.run(debug=True)

2、HTML代码




    
    Title



作者:
书籍:
{% for message in get_flashed_messages() %} {{ message }} {% endfor %}
    {% for author in authors %}
  • 作者:{{ author.name }} 删除
    • {% for book in author.books %}
    • 书籍:{{ book.name }}删除
    • {% endfor %}
    {% endfor %}

你可能感兴趣的:(Flask,flask,数据库,python)