flask图书练习

#_*_ encoding: utf-8 _*_   @author: ty  hery   2019/12/20
from  flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired


app = Flask(__name__)

#设置连接数据库的URL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:666@10.0.0.105:3306/flask_test'

# 设置每次请求结束后会自动提交数据库中的改动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# 查询时会显示原始SQL语句
app.config['SQLCHEMY_ECHO'] = True


class  Config(object):
   # 设置连接数据库的参数
   SQLALCHEMY_DATABASE_URI = "mysql://root:666@10.0.0.105:3306/flask_test"

   # 设置sqlalchemy自动跟踪数据库
   SQLALCHEMY_TRACK_MODIFICATIONS = True

   # 设置每次请求结束后会自动提交数据库中的改动
   # SQLALCHEMY_COMMIT_ON_TEARDOWN = True

   # 查询时会显示初始SQL语句
   # SQLALCHEMY_ECHO = True

   SECRET_KEY = 'doios87fsdaf7asdf6asfjljoewg'

app.config.from_object(Config)

db = SQLAlchemy(app)

class Author(db.Model):
   #  定义表名
   __tablename__='tbl_authors'

   id = db.Column(db.SmallInteger, primary_key=True)
   name = db.Column(db.String(8),unique=True)
   books = db.relationship('Book',backref='author')

class Book(db.Model):
   '''用户表'''
   __tablename__ = 'tbl_books' # 指明数据库的表名

   id = db.Column(db.SmallInteger, primary_key=True)
   name = db.Column(db.String(8),unique=True)
   author_id = db.Column(db.SmallInteger, db.ForeignKey('tbl_authors.id'))  # 外键的类型必须和他所关联的属性一致

# 创建表单模型类
class AuthorBookForm(FlaskForm):
   author_name = StringField(label=u'作者', validators=[DataRequired('作者必填')])
   book_name = StringField(label=u'书籍', validators=[DataRequired('书籍必填')])
   submit = SubmitField(label=u'保存')

print('当前的__name__ :',__name__ )


@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
       print('作者,书名: ',author_name,book_name,'------------')
       # 保存到数据库
       author_01 = Author(name=author_name)
       db.session.add(author_01)
       db.session.commit()

       book = Book(name = book_name, author_id = author_01.id)
       # book = Book(name = book_name, author = author_01) # 此处的author是反向引用的author
       db.session.add(book)
       db.session.commit()

   # 查询数据库form
   author_li = Author.query.all()
   return render_template('author_book.html', authors = author_li, form = form)


@app.route('/delete_book',methods=['POST'])
def delete_book():
   '''删除数据'''
   # 如果前端发送是请求体数据是json格式, get_json会解析成字典
   req_dict = request.get_json()
   book_id = req_dict.get('book_id')

   # 删除数据
   book = Book.query.get(book_id)
   db.session.delete(book)
   db.session.commit()

   return redirect(url_for('index'))


if __name__ == '__main__':
   # 清除数据库里的所有数据
   # db.drop_all()
   #
   # # 创建所有的表
   # db.create_all()
   #
   # # 创建对象
   # au_xi = Author(name='我吃西红柿')
   # au_qian = Author(name='萧潜')
   # au_san = Author(name='唐家三少')
   # # session记录对象任务
   # db.session.add_all([au_xi, au_qian, au_san])
   # db.session.commit()
   #
   # bk_xi = Book(name='吞噬星空',author_id=au_xi.id)
   # bk_xi2 = Book(name='寸芒',author_id=au_qian.id)
   # bk_qian = Book(name='缥缈之旅',author_id=au_qian.id)
   # bk_san = Book(name='冰火魔厨',author_id=au_san.id)
   # db.session.add_all([bk_xi, bk_xi2, bk_qian, bk_san])
   # # 提交任务到数据库中
   # db.session.commit()
   app.run(debug = True)

author_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
    {{ form.csrf_token }}

        {{ form.author_name.label }}
        <p>{{ form.author_name }}</p>
        {% for  msg in form.author_name.errors %}
            <p>{{ msg }}</p>
        {% endfor %}

    {{ form.book_name.label }}
        <p>{{ form.book_name }}</p>
        {% for msg in form.book_name.errors %}
            <p>{{ msg }}</p>
        {% endfor %}

    {{ form.submit }}
    </form>
    <hr/>

    <ul>
        {% for author in authors %}
        <li>作者:{{ author.name }}</li>

        <ul>
            {% for book in author.books %}
            <li>书籍:{{ book.name }}</li>
                <a href="javascript:;" onclick="deleteBook({{ book.id }})">删除</a>
            {% endfor %}
        </ul>
    {% endfor %}

    </ul>
    <script type="text/javascript" src="/statics\js\jquery-3.3.1.min.js"></script>

</body>
</html>
posted @ 2021-04-12 23:22  ty1539  阅读(76)  评论(0编辑  收藏  举报