项目目录
- version01
- cart
- __init__.py
- models.py
- static
- js
- jquery.min.js
- templates
- index.html
- manage.py
- settings.py
cart/__init.py
from .models import *
models.py
# 字段和字段属性
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
Base = db.Model
# 一对多关系
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False, unique=True)
class Book(Base):
__tablename__ = "books"
id = Column(Integer, primary_key=True)
book_name = Column(String(32), nullable=True)
# authors指的是tablename而不是类名
# 一对多的关系, 关联字段写在多的一方
author_id = Column(Integer, ForeignKey("authors.id")) # 可以为空
# 跟数据库无关, 不会新增字段, 只用于快速链表操作
# 类名, backref 用于反向查询
# Author.al_book可以拿到所有的Person对象
author = relationship("Author", backref="al_book")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
<label>作者</label>
<input type="text" name="author"><br /><br />
<label>书籍</label>
<input type="text" name="book">
<p style="color:red;">{
{errors}}</p>
<input type="submit" value="添加">
</form>
<hr />
<ul>
{% for auth in auths %}
<li>作者:{
{ auth.name }}</li>
{% for book in auth.al_book %}
<ul>
<li>书籍:{
{book.book_name}}</li>
<!-- <a href="/delete?book_id={
{book.id}}">删除</a>-->
<a href="javascript:;" book_id="{
{book.id}}">删除</a>
</ul>
{% endfor %}
{% endfor %}
</ul>
<script src="static/js/jquery.min.js"></script>
<script>
$(function(){
$("a").click(
function(){
var data = {
book_id: $(this).attr("book_id")
}
// 将js中的对象转换为 json字符串
var req_json = JSON.stringify(data);
$.ajax({
url: "/delete",
type: "post",
data: req_json, // 向后端发送的数据
contentType: "application/json", // 指明向后端发送的数据格式
dataType: "json", // 指明后端返回的数据格式
success: function(resp){
if(resp.code==0){
location.href = "/";
}
}
})
}
)
});
</script>
</body>
</html>
manage.py
from flask import Flask, redirect, render_template, url_for, request, jsonify
from flask_script import Manager
from flask_migrate import MigrateCommand, Migrate
from cart import db, Author, Book
app = Flask(__name__)
app.config.from_object("settings.Config")
manager = Manager(app)
db.init_app(app)
Migrate(app, db)
manager.add_command("db", MigrateCommand)
# @app.route("/")
# def index():
# b1 = Book(book_name="高数")
# b2 = Book(book_name="c++")
#
# a1 = Author(name="小王")
# a1.al_book = [b1, b2]
#
# db.session.add_all([a1])
# db.session.commit()
# return ""
@app.route("/", methods=["POST", "GET"])
def index():
errors = ""
if request.method == "POST":
author_name = request.form["author"]
book_name = request.form["book"]
if not all([author_name, book_name]):
errors = "书籍或作者不能为空"
else:
author = db.session.query(Author).filter(Author.name==author_name).first()
if author:
b = Book(book_name=book_name)
b.author = author
db.session.add(b)
db.session.commit()
else:
b = Book(book_name=book_name)
a = Author(name=author_name)
a.al_book = [b]
db.session.add_all([a])
db.session.commit()
auths = db.session.query(Author).all()
return render_template("index.html", auths=auths, errors=errors)
# @app.route("/delete")
# def delete():
#
# book_id = request.args["book_id"]
# book = db.session.query(Book).filter(Book.id==book_id)
# if book:
# book.delete()
# db.session.commit()
#
# return redirect(url_for("index"))
@app.route("/delete", methods=["POST"])
def delete():
# get_json 要求前端传送的数据的Content-Type: application/json
# 如果前端发送的请求体数据是json格式,get_json会解析成字典
req_dict = request.get_json()
book_id = req_dict.get("book_id")
book = db.session.query(Book).filter(Book.id==book_id)
if book:
book.delete()
db.session.commit()
return jsonify(code=0, message="OK")
if __name__=="__main__":
manager.run()
settings.py
class Config(object):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/item01?charset=utf8"
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 30
SQLALCHEMY_POOL_RECYCLE = -1
SQLALCHEMY_TRACK_MODIFICATIONS = True