Flask之图书管理小案例

案例运行结果

代码运行后,浏览器地址栏输入:127.0.0.1:4442即可访问此web应用小程序

在这里插入图片描述

数据库这边也实现了同步更新数据
在这里插入图片描述
在这里插入图片描述

敲码前的絮絮叨叨

项目目录结构如下
在这里插入图片描述
本小demo向页面的表单提交作者、书籍信息到数据库中;并即时把数据库中相应数据取出来显示到页面上;点击页面的删除链接,可实现把相应书籍信息或作者信息从数据库中删除。

本小demo使用Flask的扩展WTF实现表单显示,使用WTF自带的表单验证逻辑实现表单验证,并使用SQLAlchemy扩展连接数据库,并建立数据模型,通过对数据模型的操作实现对数据库的增删改查操作。

业务逻辑代码

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.secret_key = 'tuotuo'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]/flask_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(16),unique=True)
    #关系引用
    books = db.relationship("Books",backref = "author")

    def __repr__(self):
        return "author:%s" % self.name

#书籍模型
class Books(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 __repr__(self):
        return "books:%s %s" % {self.name,self.author_id}

#自定义表单类
class AuthorForm(FlaskForm):
	author = StringField("作者:",validators = [DataRequired()])
	book = StringField("书籍:",validators = [DataRequired()])
	submit = SubmitField("提交")

@app.route('/delete_author/<author_id>')
def delete_author(author_id):
	author = Author.query.get(author_id)
	if author:
		try:
			#查询书籍之后直接删除
			Books.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/<book_id>')
def delete_book(book_id):
	book = Books.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("书籍找不到")
	return redirect(url_for("index"))
@app.route('/',methods = ["GET","POST"])
def index():
	author_form = AuthorForm()
	
	if author_form.validate_on_submit():
		author_name = author_form.author.data
		book_name = author_form.book.data
		author_exist = Author.query.filter_by(name = author_name).first()
		if author_exist:
			book_exist = Books.query.filter_by(name = book_name).first()
			if book_exist:
				flash("已存在同名书籍")
			else:
				try:
					new_book = Books(name = book_name,author_id = author_exist.id)
					db.session.add(new_book)
					db.session.commit()
				except Exception as e:
					print(e)
					flash("添加书籍失败")
		else:
			try:
				new_author = Author(name=author_name)
				db.session.add(new_author)
				db.session.commit()
				new_book = Books(name=book_name, author_id=new_author.id)
				db.session.add(new_book)
				db.session.commit()
			except Exception as e:
				print(e)
				flash("添加作者和书籍失败")
	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()
    app.run("127.0.0.1",4442)

模板代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小坨的单词数据库</title>
	<style>
		body{
			background-color: aqua;
		}
		.form{
			padding:10px;
			width: 300px;
			height: 120px;
			background-color: azure;
			margin: 0 auto;
			text-align: center;

			border: 1px solid #ccc;
			box-shadow: 0 0 8px #aaa inset;
		}
		.showdata{
			padding:10px;
			width: 500px;
			height: 500px;
			background-color: azure;
			margin: 0 auto;
			overflow-y:auto;
			border: 1px solid #ccc;
			box-shadow: 0 0 8px #aaa inset;
		}


		.form input[type=submit] {
			width:40%;
			background-color: #4CAF50;
			color: white;
			padding: 6px 3px;
			margin: 3px 0;
			border: none;
			border-radius: 4px;
			cursor: pointer;
		}
		.form input{
			width: 60%;
			padding: 3px 3px;
			margin: 3px 0;
			display: inline-block;
			border: 1px solid #ccc;
			border-radius: 4px;
			box-sizing: border-box;
		}
		.space{

			height: 10px;
		}

	</style>
</head>
<body>
<h1 align="center">小坨的书籍数据库</h1>
<h2 align="center">录入数据</h2>
<div class="form">
	<form method = "POST">
		{{form.csrf_token()}}
		{{form.author.label}}{{form.author}}<br>
		{{form.book.label}}{{form.book}}<br>
		{{form.submit}}<br>

		{%for message in get_flashed_messages()%}
			{{message}}
		{%endfor%}
	</form>
</div>
<div class="space"></div>
<hr>
<div class="space"></div>
<h2 align = "center">显示数据</h2>
<div class="showdata">
	<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>
</div>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/atuo200/article/details/106482208
今日推荐