flask5
Posted zhangshuntao123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask5相关的知识,希望对你有一定的参考价值。
from flask import *
from flask_sqlalchemy import *
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField,SubmitField
from sqlalchemy import *
app = Flask(__name__)
# 连接数据库
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql://root:mysql@127.0.0.1:3306/book‘
# 动态追踪修改设置,如未设置只会提示警告
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = False
#查询时会显示原始SQL语句
# app.config[‘SQLALCHEMY_ECHO‘] = True
app.config["SECRET_KEY"]="sadasdas"
# app.config["WTF_CSRF_ENABLED"]=False
# 创建表单添加数据
class Add(FlaskForm):
au_info = StringField("AUTHOR:",validators=[DataRequired("a")])
bk_info = StringField("BOOK:",validators=[DataRequired("b")])
submit = SubmitField(‘ADD‘)
db= SQLAlchemy(app)
#定义模型类-作者
class Author(db.Model):
#定义表名
__tablename__=‘authors‘
id = db.Column(db.Integer,primary_key=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)
name = db.Column(db.String(64), unique=True)
author_id = db.Column(db.Integer,db.ForeignKey(‘authors.id‘))
@app.route(‘/‘,methods=[‘GET‘,‘POST‘])
def index():
# 返回首页
add_form = Add()
# 获取数据
if add_form.validate_on_submit():
author_name = request.form.get(‘au_info‘)
# author_name = add_form.au_info.data
print(author_name)
book_name = request.form.get(‘bk_info‘)
# 判断数据是否存在数据库中
author = Author.query.filter(Author.name == author_name).first()
if not author:
try:
# 先添加作者
author = Author(name=author_name)
db.session.add(author)
db.session.commit()
# 后添加书
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:
book = Author.query.filter(Book.name == book_name).first()
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:
if request.method == "POST":
flash("添加错误")
author = Author.query.all()
# book = Book.query.all()
return render_template(‘book.html‘,authors=author,form=add_form)
@app.route(‘/delete_author/<int:author_id>‘)
# 删除作者
def delete_author(author_id):
# 获取数据
author = Author.query.get(author_id)
if not author:
flash("miss错误")
else:
try:
Book.query.filter_by(author_id = author.id).delete()
db.session.delete(author)
# db.session.delete(author_id)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
flash("no success")
return redirect(url_for(‘index‘))
# 删除书籍
@app.route(‘/delete_book/<int:book_id>‘)
def delete_book(book_id):
print("dsfsdf")
book = Book.query.get(book_id)
print(book)
if not book:
flash("miss错误 ")
else:
print(‘111111‘)
try:
print("222222")
book_Id = Book.query.filter(Book.id == book.id).first()
db.session.delete(book_Id)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
flash("no success")
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,port=4567)
以上是关于flask5的主要内容,如果未能解决你的问题,请参考以下文章