后台
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 InputRequired, DataRequired
app = Flask(__name__)
app.secret_key = 'asdffsdaf1111sdfa11sdfdsa'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:3Dmax2012#@127.0.0.1:3306/test3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class AddBook(FlaskForm):
author_name = StringField(label='作者名字', validators=[InputRequired()])
book_name = StringField(label='书籍名称', validators=[DataRequired()])
submit = SubmitField('调价')
class Author(db.Model):
__tablename__ = 'authors'
id = db.Column(db.Integer, primary_key=True, autoincrement=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, autoincrement=True)
name = db.Column(db.String(64), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey(Author.id))
@app.route("/", methods=['GET', 'POST'])
def index():
# 使用wtf 表单
bookform = AddBook()
# 增加书籍
if request.method == 'POST':
if bookform.validate_on_submit():
author_name = request.form.get('author_name')
book_name = request.form.get('book_name')
author = Author.query.filter(Author.name == author_name).first()
book = Book.query.filter(Book.name == book_name).first()
if not author:
try:
author = Author(name=author_name)
db.session.add(author)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
if not book:
try:
book = Book(name=book_name, author_id=author.id)
db.session.add(book)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
flash("添加失败")
else:
flash('你输入的已经重复')
else:
# if request.method=='POST':
flash("参数错误")
# 查询数据
authors = Author.query.filter(Author.id.in_((book.author_id for book in Book.query.all())))
# 渲染模板
return render_template('template8.html', authors=authors, form=bookform)
@app.route('/delete/author/<author_id>')
def delauthor(author_id):
# 根据author_id 查询 作者
# 如果存在,就直接删除作者及其书籍
# 若果不存在,则返回不存在
author = Author.query.get(author_id)
if not author:
return "作者不存在"
try:
for book in author.books:
db.session.delete(author)
db.session.delete(author)
db.session.commit()
except Exception as e:
print(e)
db.session.rollback()
return '删除作者书籍失败'
return redirect(url_for("index"))
@app.route("/delete/book/<book_id>")
def delbook(book_id):
# 根据author_id,book_id 查询 作者,书籍
# 如果存在,就直接删除作者及其书籍
# 返回参数不合法
# 若果不存在,则返回不存在
book = Book.query.filter(Book.id == book_id).first()
if not book:
return "书籍不存在"
try:
db.session.delete(book)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
return redirect(url_for("index"))
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</title>
</head>
<body>
<form action="" method="post">
{{ form.csrf_token }}
{{ form.author_name.label }} {{ form.author_name }} <br>
{{ form.book_name.label }} {{ form.book_name }} <br>
{{ form.submit }}
</form>
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
<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>