一、知识点:
- 表单创建
- 数据库操作
- 一对多关系演练
二、实现步骤:
- 创建数据库配置信息,定义模型类
- 创建数据库表,添加测试数据
- 编写html页面,展示数据
- 添加数据
- 删除书籍,删除作者
三、创建数据库连接信息,定义模型
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
CSRFProtect(app)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:[email protected]:3306/library2"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = "jfkdjfkdkjf"
class Author(db.Model):
__tablename__ = 'authors'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),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(64),unique=True)
author_id = db.Column(db.Integer,db.ForeignKey('authors.id'))
@app.route('/add_book', methods=['POST'])
def add_book():
"""
思路分析:
1.获取参数
2.校验参数
3.通过作者名称,查询作者对象
4.判断作者,判断书籍,进行添加
5.重定向展示页
:return:
"""
author_name = request.form.get("author")
book_name = request.form.get("book")
if not all([author_name,book_name]):
return "作者或者书籍为空"
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(url_for('show_page'))
@app.route('/delete_book/')
def delete_book(book_id):
book = Book.query.get(book_id)
db.session.delete(book)
db.session.commit()
return redirect(url_for('show_page'))
@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(url_for('show_page'))
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask,render_template,flash,request
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://root:[email protected]/flask_books'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'Zep03'
db = SQLAlchemy(app)
'''
1. 配置数据库
a.导入SQLAlchemy扩展
b.创建db对象,并配置参数
c.通过mysql终端创建数据库
2. 添加书和作者的模型
a.模型要继承db.Model
b.__tablaname__:定义表名
c.db.Column:定义字段名
d.db.relationship: 关系引用
3. 添加数据
4. 使用模板显示数据库查询的数据
a.查询所有的作者信息,将信息传递给模板
b.模板中按照格式,一次for循环作者和书籍即可(作者获取书籍,用的是关系引用)
5. 使用WTF显示表单
a.自定义表单类
b.模板中显示
c.设置secret_key/解决编码问题/csrf_token
6. 实现相关的增删逻辑
a.增加数据
'''
class Author(db.Model):
__tablename__ = 'authors'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(16),unique=True)
books = db.relationship('Book',backref='author')
def __refr__(self):
return 'Author: %s ' % self.name
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), unique=True)
author_id = db.Column(db.Integer,db.ForeignKey('authors.id'))
def __refr__(self):
return 'Book: %s %s ' % self.name,self.author_id
class AuthorForm(FlaskForm):
author = StringField('作者',validators=[DataRequired()])
book = StringField('书籍',validators=[DataRequired()])
submit = SubmitField('提交')
@app.route('/',methods=['GET','POST'])
def index():
author_form = AuthorForm()
'''
验证逻辑:
1. 调用WTF的函数实现验证
2. 验证通过获取数据
3. 判断作者是否存在
4. 如果作者存在,判断书籍是否存在,没有重复书籍就添加书籍信息;如果重复就提示错误
5. 如果作者不存在,添加作者和书籍
6. 验证不通过就提示错误
'''
if author_form.validate_on_submit():
author_name = author_form.author.data
book_name = author_form.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('参数不全')
authors = Author.query.all()
return render_template('books.html',authors= authors,form = author_form)
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)
四、创建表,添加测试数据
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)
五、数据显示&表单添加
@app.route('/')
def show_page():
authors = Author.query.all()
return render_template('library.html',authors=authors)
- 前端代码
- 创建文件 library.html ,编写以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{
<form action="/add_book" method="post">
{
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<p>
<label>作者</label><input type="text" name="author"><br>
</p>
<p>
<label>书籍</label><input type="text" name="book"><br>
</p>
<p>
<input type="submit" value="添加">
</p>
{% for message in get_flashed_messages() %}
<span style="color: red">{{ message }}</span>
{% endfor %}
</form>
<hr>
{
<h2>书籍展示</h2>
<ul>
{% for author in authors %}
<li>作者: {{ author.name }} <a href="{{ url_for('delete_author',author_id=author.id) }}">删除</a></li><br>
<ul>
{% for book in author.books %}
<li>书籍: {{ book.name }} <a href="{{ url_for('delete_book',book_id=book.id) }}">删除</a></li><br>
{% endfor %}
</ul>
{% endfor %}
</ul>
</body>
</html>
六、添加数据
@app.route('/add_book', methods=['POST'])
def add_book():
"""
思路分析:
1.获取参数
2.校验参数
3.通过作者名称,查询作者对象
4.判断作者,判断书籍,进行添加
5.重定向展示页
:return:
"""
author_name = request.form.get("author")
book_name = request.form.get("book")
if not all([author_name,book_name]):
return "作者或者书籍为空"
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(url_for('show_page'))
七、删除数据
@app.route('/delete_book/')
def delete_book(book_id):
book = Book.query.get(book_id)
db.session.delete(book)
db.session.commit()
return redirect(url_for('show_page'))
@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(url_for('show_page'))
八、案例完整代码
from flask import Flask,render_template,flash,request,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://root:[email protected]/flask_books'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'Zep03'
db = SQLAlchemy(app)
'''
1. 配置数据库
a.导入SQLAlchemy扩展
b.创建db对象,并配置参数
c.通过mysql终端创建数据库
2. 添加书和作者的模型
a.模型要继承db.Model
b.__tablaname__:定义表名
c.db.Column:定义字段名
d.db.relationship: 关系引用
3. 添加数据
4. 使用模板显示数据库查询的数据
a.查询所有的作者信息,将信息传递给模板
b.模板中按照格式,一次for循环作者和书籍即可(作者获取书籍,用的是关系引用)
5. 使用WTF显示表单
a.自定义表单类
b.模板中显示
c.设置secret_key/解决编码问题/csrf_token
6. 实现相关的增删逻辑
a.增加数据
b.删除书籍——》网页中删除——》点击需要发送书籍的ID给删除书籍的路由——》路由需要接收参数
url_for的使用 / for else的使用 / redirect的使用
c.删除作者
'''
class Author(db.Model):
__tablename__ = 'authors'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(16),unique=True)
books = db.relationship('Book',backref='author')
def __refr__(self):
return 'Author: %s ' % self.name
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), unique=True)
author_id = db.Column(db.Integer,db.ForeignKey('authors.id'))
def __refr__(self):
return 'Book: %s %s ' % self.name,self.author_id
class AuthorForm(FlaskForm):
author = StringField('作者',validators=[DataRequired()])
book = StringField('书籍',validators=[DataRequired()])
submit = SubmitField('提交')
@app.route('/delete_author/')
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('index'))
@app.route('/delete_book/')
def delete_book(book_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('书籍找不到~')
print(url_for('index'))
return redirect(url_for('index'))
@app.route('/',methods=['GET','POST'])
def index():
author_form = AuthorForm()
'''
验证逻辑:
1. 调用WTF的函数实现验证
2. 验证通过获取数据
3. 判断作者是否存在
4. 如果作者存在,判断书籍是否存在,没有重复书籍就添加书籍信息;如果重复就提示错误
5. 如果作者不存在,添加作者和书籍
6. 验证不通过就提示错误
'''
if author_form.validate_on_submit():
author_name = author_form.author.data
book_name = author_form.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('参数不全')
authors = Author.query.all()
return render_template('books.html',authors= authors,form = author_form)
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)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书管理</title>
</head>
<body>
<form method="post">
{{ form.csrf_token() }}
{{ form.author.label }} {{ form.author }} <br>
{{ form.book.label }} {{ form.book }} <br>
{{ form.submit }} <br>
</form>
<!-- 显示消息闪现的内容-->
{% for message in get_flashed_messages() %}
{{message}}
{% endfor %}
<hr>
<!-- 先遍历作者,然后在作者里遍历书籍-->
<ul>
{% for author in authors %}
<li>{{author.name}} <a href="{{url_for('delete_author', author_id = author.id)}}">删除</a></li>
<ul>
{% for book in author.books %}
<li>{{book.name}} <a href="{{url_for('delete_book', book_id = book.id)}}">删除</a></li>
{% else %}
<li>无</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</body>
</html>
第一种 删除书籍的实现方法(通过post请求来实现)
from flask import Flask,render_template,request,redirect,url_for,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
import json
app = Flask(__name__)
class Config(object):
'''配置参数'''
SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/author_book_py04"
SQLALCHEMY_TRACK_MODIFICATIONS = True
SECRET_KEY = "JDIOGDKFNKXNCV12345D4FSDFS"
app.config.from_object(Config)
db = SQLAlchemy(app)
class Author(db.Model):
'''作者表'''
__tablename__ = "tbl_authors"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32),unique=True)
books = db.relationship("Book",backref = "author")
class Book(db.Model):
'''作者表'''
__tablename__ = "tbl_books"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
author_id = db.Column(db.Integer,db.ForeignKey('tbl_authors.id'))
class AuthorBookForm(FlaskForm):
'''作者书籍表单模型类'''
author_name = StringField(label="作者:",validators=[DataRequired("作者必填!")])
book_name = StringField(label="书名:",validators=[DataRequired("书名必填!")])
submit = SubmitField(label="保存")
@app.route("/index",methods=["GET","POST"])
def index():
form = AuthorBookForm()
if form.validate_on_submit():
author_name = form.author_name.data
book_name = form.book_name.data
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()
author_li = Author.query.all()
return render_template("author_book.html",authors = author_li,form=form)
@app.route("/delete_book",methods=["POST"])
def delete_book():
req_dict = request.get_json()
book_id = req_dict.get("book_id")
book = Book.query.get(book_id)
db.session.delete(book)
db.session.commit()
return jsonify(code=0,message="OK")
if __name__ == '__main__':
db.drop_all()
db.create_all()
au_xi = Author(name='我吃西红柿')
au_qian = Author(name='萧潜')
au_san = Author(name='唐家三少')
db.session.add_all([au_xi,au_qian,au_san])
db.session.commit()
bk_xi = Book(name='吞噬星空',author_id=au_xi.id)
bk_xi2 = Book(name='寸芒',author_id=au_qian.id)
bk_qian = Book(name='飘渺之旅',author_id=au_qian.id)
bk_san = Book(name='冰火魔厨',author_id=au_san.id)
db.session.add_all([bk_xi,bk_xi2,bk_qian,bk_san])
db.session.commit()
app.run(debug=True)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form method="post">
{{form.csrf_token}}
{{form.author_name.label}}
<p>{{form.author_name}}p>
{% for msg in form.author_name.errors %}
<p>{{msg}}p>
{% endfor %}
{{form.book_name.label}}
<p>{{form.book_name}}p>
{% for msg in form.book_name.errors %}
<p>{{msg}}p>
{% endfor %}
{{form.submit}}
form>
<hr>
<ul>
{% for author in authors %}
<li>作者:{{author.name}}li>
<ul>
{% for book in author.books %}
<li>书籍:{{book.name}}li>
<a href="javascript:;" book-id="{{book.id}}">删除a>
{% endfor %}
ul>
{% endfor %}
ul>
<script src="../static/js/jquery-3.5.0.js">script>
<script>
$("a").click(function () {
var data = {
book_id:$(this).attr("book-id")
};
var req_json = JSON.stringify(data)
$.ajax({
url:"/delete_book",
type:"post",
data:req_json,
contentType:"application/json",
dataType:"json",
success:function (resp) {
if (resp.code == 0) {
alert("ok")
location.href = "/index";
}
}
})
})
script>
body>
html>
重点解读:
第二种 删除书籍的实现方法(通过get请求来实现)
from flask import Flask,render_template,request,redirect,url_for,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
import json
app = Flask(__name__)
class Config(object):
'''配置参数'''
SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/author_book_py04"
SQLALCHEMY_TRACK_MODIFICATIONS = True
SECRET_KEY = "JDIOGDKFNKXNCV12345D4FSDFS"
app.config.from_object(Config)
db = SQLAlchemy(app)
class Author(db.Model):
'''作者表'''
__tablename__ = "tbl_authors"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32),unique=True)
books = db.relationship("Book",backref = "author")
class Book(db.Model):
'''作者表'''
__tablename__ = "tbl_books"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
author_id = db.Column(db.Integer,db.ForeignKey('tbl_authors.id'))
class AuthorBookForm(FlaskForm):
'''作者书籍表单模型类'''
author_name = StringField(label="作者:",validators=[DataRequired("作者必填!")])
book_name = StringField(label="书名:",validators=[DataRequired("书名必填!")])
submit = SubmitField(label="保存")
@app.route("/index",methods=["GET","POST"])
def index():
form = AuthorBookForm()
if form.validate_on_submit():
author_name = form.author_name.data
book_name = form.book_name.data
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()
author_li = Author.query.all()
return render_template("author_book.html",authors = author_li,form=form)
@app.route("/delete_book",methods=["GET"])
def delete_book():
book_id = request.args.get("book_id")
book = Book.query.get(book_id)
db.session.delete(book)
db.session.commit()
return redirect(url_for("index"))
if __name__ == '__main__':
db.drop_all()
db.create_all()
au_xi = Author(name='我吃西红柿')
au_qian = Author(name='萧潜')
au_san = Author(name='唐家三少')
db.session.add_all([au_xi,au_qian,au_san])
db.session.commit()
bk_xi = Book(name='吞噬星空',author_id=au_xi.id)
bk_xi2 = Book(name='寸芒',author_id=au_qian.id)
bk_qian = Book(name='飘渺之旅',author_id=au_qian.id)
bk_san = Book(name='冰火魔厨',author_id=au_san.id)
db.session.add_all([bk_xi,bk_xi2,bk_qian,bk_san])
db.session.commit()
app.run(debug=True)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form method="post">
{{form.csrf_token}}
{{form.author_name.label}}
<p>{{form.author_name}}p>
{% for msg in form.author_name.errors %}
<p>{{msg}}p>
{% endfor %}
{{form.book_name.label}}
<p>{{form.book_name}}p>
{% for msg in form.book_name.errors %}
<p>{{msg}}p>
{% endfor %}
{{form.submit}}
form>
<hr>
<ul>
{% for author in authors %}
<li>作者:{{author.name}}li>
<ul>
{% for book in author.books %}
<li>书籍:{{book.name}}li>
<a href="/delete_book?book_id={{book.id}}" >GET删除a>
{% endfor %}
ul>
{% endfor %}
ul>
<script src="../static/js/jquery-3.5.0.js">script>
<script>
script>
body>
html>
重点解读: