Flask CURD

book.py

 


 

 from flask import Blueprint,render_template,request,session,redirect,url_for # redirect ,url_for重定向跳转

book = Blueprint('book',__name__) #模块名/蓝图名叫users

from .models import Books,Users

@book.route('/list',methods=['GET','POST']) # 路由定义!

def index():

  if request.method=='GET':

    paginate = Books.query.paginate(1,3)# 默认查询第1页

    page = int(request.args.get('page',1))

    if page<0:

      page = 1

    if page >= paginate.pages: # 判断是否大于总页数

      page = paginate.

    pages paginate = Books.query.paginate(page,3)

    books = paginate.items #当前页数据

    return render_template('/books.html',books=books,paginate=paginate) # 跳转到模板!

  else:

    print('模糊查询')

    name = request.form.get('name') # 书名

    #paginate = Books.query.filter(Books.name.contains(name)).paginate(1, 3)

    paginate = Books.query.filter(Books.name.like("%"+name+"%")).paginate(1, 3)

    books = paginate.items # 当前页数据

    return render_template('/books.html', books=books, paginate=paginate,name=name) # 跳转到模板!

# 增删改查

@book.route("/add_author", methods=["POST"])

  def add_author():

  # 获取前端传递过来的数据

  name = request.form.get("name")

  email = request.form.get("email")

 

  # 实例化对象

  author = Author()

 

  # 设置属性值

  author.name = name

  author.email = email

 

  # 将对象添加到会话中

  db.session.add(author)

 

  # 提交事务

  db.session.commit()

  return "add author success"

 

@book.route("/update_author", methods=["POST"])

def update_author():

  # 获取前端传递过来的数据

  name = request.form.get("name")

  email = request.form.get("email")

 

  author = Author.query.filter_by(name=name).first()

  print("author=", author)

 

  # 修改对象的属性

  author.email = email

 

  # 修改对象时不需要手动将对象添加到会话中,因为查询时已经将对象纳入会话管理中

  db.session.commit()

  return "update author success"

 

@book.route("/delete_author")

def delete_author():

  id = request.args.get("id")

  print("id=", id)

  

  # 查询对象

  author = Author.query.get(id)

 

  # 通过调用会话对象的delete()指定要执行删除操作

  db.session.delete(author)

 

  # 提交事务

  db.session.commit()

 

  return "delete author success"

 

@book.route("/query_author")

def query_author():

  authors = Author.query.all()

  print("authors=", authors)

 

  return "query authors success"

 

@book.route("/add_book", methods=["POST"])

def add_book():

  # 获取客户端发送过来的数据

  name = request.form.get("name")

  author_id = request.form.get("author_id")

 

  book = Book()

  book.name = name

  book.author_id = author_id

  db.session.add(book)

  db.session.commit()

 

  return "add book success"

 

@book.route("/query_books")

def query_books():

  books = Book.query.all()

  print("books=", books)

 

  return jsonify(code=0, message="ok")


数据库迁移

# 一定要先使用一遍再进行迁移

python manage.py db init

python manage.py db migrate

python manage.py db upgrate

 


 

model.py

 

 

 

 

posted @ 2020-11-09 18:51  ttpython  阅读(93)  评论(0)    收藏  举报