图书
from flask import Flask, render_template, request, flash,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+mysqlconnector://root:111111@127.0.0.1:3306/flask_books"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.secret_key = "xxxx"
db = SQLAlchemy(app)
class LoginForm(FlaskForm):
book = StringField("书籍", validators=[DataRequired()])
author = StringField("作者", validators=[DataRequired()])
submit = SubmitField("提交")
class Author(db.Model):
# 表名
__tablename__ = "authors"
# 字段
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), 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(20), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey('authors.id'))
@app.route('/delete_author/<author_id>')
def delete_author(author_id):
author = Author.query.get(author_id)
if author:
try:
Book.query.filter_by(author_id=author.id).delete() # 查询后直接删除
db.session.delete(author)
db.session.commit()
except Exception as e:
print(e)
flash('删除作者错误')
db.session.rollback()
else:
flash('作者找不到')
return redirect(url_for('hello_world'))
@app.route('/delete_book/<book_id>')
def delete_book(book_id):
# 查询当前数据库,是否有该ID的书,如果有就删除,没有就提示错误
book = Book.query.get(book_id)
if book:
try:
db.session.delete(book)
db.session.commit()
except Exception as e:
print(e)
flash('删除书籍出错')
db.session.rollback()
else:
flash('书籍找不到')
# 返回当前网址-->重定向
# url_for('hello_world')需要传入视图函数名,返回该视图函数对应的路由地址
return redirect(url_for('hello_world')) # redirect重定向,需要传入网址/路由地址
@app.route('/', methods=["POST", "GET"])
def hello_world():
logform = LoginForm() # 在视图函数值创建表单
if logform.validate_on_submit():
author_name = logform.author.data # 提取表单数据
book_name = logform.book.data
author = Author.query.filter_by(name=author_name).first() # 判断作者是否存在
if author: # 判断书籍是否存在,没有重复书记就添加数据,如果重复就提示错误
book = Book.query.filter_by(name=book_name).first()
if book:
flash('已存在重名书籍')
else:
try:
new_book = Book(name=book_name,author_id=author.id)
db.session.add(new_book)
db.session.commit()
except Exception as e:
print(e)
flash('添加书籍失败')
db.session.rollback()
else: # 如果作者不存在,添加作者和书籍
try:
new_author=Author(name=author_name)
db.session.add(new_author)
db.session.commit()
new_book=Book(name=book_name, author_id=new_author.id)
db.session.add(new_book)
db.session.commit()
except Exception as e:
print(e)
flash('添加书籍作者失败')
db.session.rollback()
else:
if request.method == "POST":
flash("参数有误")
author = Author.query.all() # 在哪个模型中查询
return render_template("book.html", author=author, form=logform)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body {
background-image: url("/static/QQ图片20181223112355.jpg");
}
</style>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>图书管理系统</h1>
<form method="post">
{{ form.csrf_token() }}
{{ form.author.label }}{{ form.author }}<br>
{{ form.book.label }}{{ form.book }}<br>
{{ form.submit }}<br>
{% for flashed_message in get_flashed_messages() %}
{{ flashed_message }}
{% endfor %}
<hr/>
{% for authors in author %}
<li>作者:{{ authors.name }}<a href="{{ url_for("delete_author",author_id=authors.id) }}">删除</a></li>
<ul>
{% for book in authors.books %}
<li>书籍:{{ book.name }} <a href="{{ url_for("delete_book",book_id=book.id) }}">删除</a></li>
{% else %}
<li>无</li>
{% endfor %}
</ul>
{% endfor %}
</form>
</body>
</html>