文件目录结构
./ ├── main.py ├── templates │ └── index.html └── static └── js └── jquery-3.3.1.min.js
一共涉及三个文件
1、jquery-3.3.1.min.js 可百度下载
2、 main.py
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, url_for, redirect, jsonify from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired app = Flask(__name__) # 配置数据库信息 class Config(object): SQLALCHEMY_DATABASE_URI = "mysql://root:123456@127.0.0.1:3306/demo" SQLALCHEMY_TRACK_MODIFICATIONS = True SECRET_KEY = "adsfasdf9932@@fdsafsdaf" app.config.from_object(Config) db = SQLAlchemy(app) class Author(db.Model): """作者""" __tablename__ = "tbl_author" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) books = db.relationship("Book", backref="author") class Book(db.Model): """书籍""" __tablename__ = "tbl_book" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) author_id = db.Column(db.Integer, db.ForeignKey("tbl_author.id")) def db_init(): """ 初始化数据库 mysql> create database demo default charset utf8; """ db.drop_all() db.create_all() author1 = Author(name="吴承恩") author2 = Author(name="施耐庵") author3 = Author(name="罗贯中") author4 = Author(name="曹雪芹") db.session.add_all([author1, author2, author3, author4]) db.session.commit() book1 = Book(name="西游记", author=author1) book2 = Book(name="红楼梦", author=author4) book3 = Book(name="三国演义", author=author3) book4 = Book(name="水浒传", author=author2) db.session.add_all([book1, book2, book3, book4]) db.session.commit() class AuthorBookForm(FlaskForm): """作者书籍表单""" author_name = StringField(label="作者姓名", validators=[DataRequired("作者姓名不能为空")]) book_name = StringField(label="书籍名称", validators=[DataRequired("书籍名称不能为空")]) submit = SubmitField(label="提交") # 视图函数 @app.route("/", 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=author) db.session.add(book) db.session.commit() # 查询数据 authors = Author.query.all() return render_template("index.html", authors=authors, form=form) @app.route("/deleteBook", methods=["POST"]) def delete_book(): """删除书本数据 接收json格式的数据 contentType: application/json """ data = request.json book_id = data.get("bookId") book = Book.query.get(book_id) db.session.delete(book) db.session.commit() data = { "code": 0, "message": "delete success" } return jsonify(data) @app.route("/deleteAuthor") def delete_author(): """删除作者书籍""" author_id = request.args.get("authorId") author = Author.query.get(author_id) db.session.delete(author) db.session.commit() return redirect(url_for("index")) if __name__ == '__main__': # db_init() app.run(debug=True)
3、index.html
<!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 }} {% for msg in form.author_name.errors %} {{ msg }} {% endfor %} {{ form.book_name.label }} {{ form.book_name }} {% for msg in form.book_name.errors %} {{ msg }} {% endfor %} {{ form.submit }} </form> <hr/> <!-- 显示作者书籍 --> <ul> {% for author in authors %} <li> 作者:{{ author.name }} <a href="/deleteAuthor?authorId={{ author.id }}">删除</a> <ul> {% for book in author.books %} <li>书籍:{{ book.name }} <a href="javascript:" onclick="deleteBook({{ book.id }})">删除</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> <script type="text/javascript" src="/static/js/jquery-3.3.1.min.js"></script> <script> function deleteBook(bookId) { var data = { bookId: bookId }; // 向后端发送json格式数据 $.ajax({ url: "/deleteBook", // 请求url type: "post", // 请求方式 data: JSON.stringify(data), //向后端发送的请求体数据,将js对象转为json字符串 contentType: "application/json",//向后端发送的数据格式 dataType: "json", // 后端返回的数据格式 success: function (result) { if (result.code === 0) { location.href = "/"; } } }) } </script> </body> </html>
显示效果