赞
踩
图书管理系统:
# 作者表
class Author(db.Model):
__tablename__ = "authors"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(48), unique=True)
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(48), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey("authors.id")) # 设置外键
2.1 python代码
from flask import Flask, render_template, request, flash, redirect, url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = 'test' # 设置数据库的连接地址 app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/db_books" # 是否监听数据库变化 一般不打开, 比较消耗性能 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # 创建数据库操作对象(建立了数据库连接) db = SQLAlchemy(app) # 作者表 class Author(db.Model): __tablename__ = "authors" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(48), unique=True) 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(48), unique=True) author_id = db.Column(db.Integer, db.ForeignKey("authors.id")) # 设置外键 @app.route("/", methods=['GET', 'POST']) def index() # 查询出所有的作者和书籍信息 authors = Author.query.all() return render_template('book_test.html', authors=authors) if __name__ == '__main__': # 会删除所有继承db.Model的表 db.drop_all() # 会创建所有继承自db.Model的表 db.create_all() # 生成数据 au1 = Author(name='金庸') au2 = Author(name='古龙') au3 = Author(name='梁羽生') bk1 = Book(name='《神雕侠侣》') bk2 = Book(name='《天龙八部》') bk3 = Book(name='《鹿鼎记》') bk4 = Book(name='《浣花洗剑录》') bk5 = Book(name='《多情剑客无情剑》') bk6 = Book(name='《七剑下天山》') bk7 = Book(name='《白发魔女传》') au1.books.append(bk1) au1.books.append(bk2) au1.books.append(bk3) au2.books.append(bk4) au2.books.append(bk5) au3.books.append(bk6) au3.books.append(bk7) # 把数据提交给用户会话 db.session.add_all([au1, au2, au3]) db.session.add_all([bk1, bk2, bk3, bk4, bk5, bk6, bk7]) # 提交会话 db.session.commit() app.run(debug=True)
2.2模板html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>图书管理</h1> <form method="post"> <label>作者名: </label><input type="text" name="author_name" placeholder="请输入作者名"><br/> <label>书名: </label><input type="text" name="book_name" placeholder="请输入书名"><br/> <input type="submit" value="保存"> </form> <hr> <ul> {% for author in authors %} <li>{{ author.name }}<a href="/delete_author/{{ author.id }}"> 删除</a></li> <ul> {% for book in author.books %} <li>{{ book.name }} <a href="/delete_book/{{ book.id }}"> 删除</a></li> {% endfor %} </ul> {% endfor %} </ul> </body> </html>
2.3界面效果图
@app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'GET': try: # 查询出所有的作者和书籍信息 authors = Author.query.all() except BaseException as e: flash("数据库查询失败") return redirect(url_for('index')) # 将数据传入模板,进行模板渲染 return render_template('book_test.html', authors=authors) # POST处理 author_name = request.form.get("author_name") book_name = request.form.get("book_name") # all([]) 如果列表中的元素都有值(不是0/NONE/空字符串),否则返回True if not all([author_name, book_name]): flash('参数不完整') return redirect(url_for('index')) try: # 判断作者是否存在 author = Author.query.filter_by(name=author_name).first() if author: # 有作者,创建书籍模型,建立关联,添加到数据库里 # 设计表时书名设置为unique,所以判断书籍名是否存在 book = Book.query.filter_by(name=book_name).first() if book: flash("书籍已存在") return redirect(url_for('index')) new_book = Book(name=book_name) author.books.append(new_book) db.session.add(new_book) db.session.commit() else: # 无作者,创建作者书籍模型,建立关联,添加到数据库里 # 设计表时书名设置为unique,所以判断书籍名是否存在 book = Book.query.filter_by(name=book_name).first() if book: flash("书籍已存在") return redirect(url_for('index')) new_author = Author(name=author_name) new_book = Book(name=book_name) new_author.books.append(new_book) db.session.add_all([new_author, new_book]) db.session.commit() except BaseException as e: print(e) flash('数据库操作失败') # 数据库增删改操作失败时,需要回滚 db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/delete_book/<int:book_id>') def delete_book(book_id): try: # 根据传过来的book_id 查询到book对象进行删除 book = Book.query.get(book_id) # 删除数据 db.session.delete(book) db.session.commit() flash('删除成功') except BaseException as e: print(e) flash('数据库操作失败') db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/delete_author/<int:author_id>') def delete_author(author_id): try: # 根据传过来的author_id 查询到author对象 author = Author.query.get(author_id) # 查询作者名下的书籍模型 books = author.books # 遍历删除 for book in books: db.session.delete(book) # 删除数据 db.session.delete(author) db.session.commit() flash('删除成功') except BaseException as e: print(e) flash('数据库操作失败') db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index'))
这样就完成了一个简单的flask的图书管理的实例.
""" 图书管理系统: 1. 实现图书和作者的添加功能 2. 实现动态查询显示图书信息 3. 实现删除功能 """ from flask import Flask, render_template, request, flash, redirect, url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = 'test' # 设置数据库的连接地址 app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/db_books" # 是否监听数据库变化 一般不打开, 比较消耗性能 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # 创建数据库操作对象(建立了数据库连接) db = SQLAlchemy(app) # 作者表 class Author(db.Model): __tablename__ = "authors" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(48), unique=True) 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(48), unique=True) author_id = db.Column(db.Integer, db.ForeignKey("authors.id")) # 设置外键 @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'GET': try: # 查询出所有的作者和书籍信息 authors = Author.query.all() except BaseException as e: flash("数据库查询失败") return redirect(url_for('index')) # 将数据传入模板,进行模板渲染 return render_template('book_test.html', authors=authors) # POST处理 author_name = request.form.get("author_name") book_name = request.form.get("book_name") # all([]) 如果列表中的元素都有值(不是0/NONE/空字符串),否则返回True if not all([author_name, book_name]): flash('参数不完整') return redirect(url_for('index')) try: # 判断作者是否存在 author = Author.query.filter_by(name=author_name).first() if author: # 有作者,创建书籍模型,建立关联,添加到数据库里 # 设计表时书名设置为unique,所以判断书籍名是否存在 book = Book.query.filter_by(name=book_name).first() if book: flash("书籍已存在") return redirect(url_for('index')) new_book = Book(name=book_name) author.books.append(new_book) db.session.add(new_book) db.session.commit() else: # 无作者,创建作者书籍模型,建立关联,添加到数据库里 # 设计表时书名设置为unique,所以判断书籍名是否存在 book = Book.query.filter_by(name=book_name).first() if book: flash("书籍已存在") return redirect(url_for('index')) new_author = Author(name=author_name) new_book = Book(name=book_name) new_author.books.append(new_book) db.session.add_all([new_author, new_book]) db.session.commit() except BaseException as e: print(e) flash('数据库操作失败') # 数据库增删改操作失败时,需要回滚 db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index')) @app.route('/delete_book/<int:book_id>') def delete_book(book_id): try: # 根据传过来的book_id 查询到book对象进行删除 book = Book.query.get(book_id) # 删除数据 db.session.delete(book) db.session.commit() flash('删除成功') except BaseException as e: print(e) flash('数据库操作失败') db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index')) @app.route('/delete_author/<int:author_id>') def delete_author(author_id): try: # 根据传过来的author_id 查询到author对象 author = Author.query.get(author_id) # 查询作者名下的书籍模型 books = author.books # 遍历删除 for book in books: db.session.delete(book) # 删除数据 db.session.delete(author) db.session.commit() flash('删除成功') except BaseException as e: print(e) flash('数据库操作失败') db.session.rollback() return redirect(url_for('index')) return redirect(url_for('index')) if __name__ == '__main__': # 会删除所有继承db.Model的表 db.drop_all() # 会创建所有继承自db.Model的表 db.create_all() # 生成数据 au1 = Author(name='金庸') au2 = Author(name='古龙') au3 = Author(name='梁羽生') bk1 = Book(name='《神雕侠侣》') bk2 = Book(name='《天龙八部》') bk3 = Book(name='《鹿鼎记》') bk4 = Book(name='《浣花洗剑录》') bk5 = Book(name='《多情剑客无情剑》') bk6 = Book(name='《七剑下天山》') bk7 = Book(name='《白发魔女传》') au1.books.append(bk1) au1.books.append(bk2) au1.books.append(bk3) au2.books.append(bk4) au2.books.append(bk5) au3.books.append(bk6) au3.books.append(bk7) # 把数据提交给用户会话 db.session.add_all([au1, au2, au3]) db.session.add_all([bk1, bk2, bk3, bk4, bk5, bk6, bk7]) # 提交会话 db.session.commit() app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>图书管理</h1> <form method="post"> <label>作者名: </label><input type="text" name="author_name" placeholder="请输入作者名"><br/> <label>书名: </label><input type="text" name="book_name" placeholder="请输入书名"><br/> <input type="submit" value="保存"> </form> <hr> <ul> {% for author in authors %} <li>{{ author.name }}<a href="/delete_author/{{ author.id }}"> 删除</a></li> <ul> {% for book in author.books %} <li>{{ book.name }} <a href="/delete_book/{{ book.id }}"> 删除</a></li> {% endfor %} </ul> {% endfor %} </ul> {% for msg in get_flashed_messages() %} <script>alert("{{ msg }}")</script> {% endfor %} </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。