06-綜合案例(一對多)

綜合案例-圖書管理

  一、WTF表單html

  二、數據庫操做mysql

  三、一對多關係演練sql

定義模型

  模型表示程序使用的數據實體,在Flask-SQLAlchemy中,模型通常是Python類,繼承自db.Model,db是SQLAlchemy類的實例,表明程序使用的數據庫。數據庫

  類中的屬性對應數據庫表中的列。id爲主鍵,是由Flask-SQLAlchemy管理。db.Column類構造函數的第一個參數是數據庫列和模型屬性類型。flask

若是想修改數據庫編碼:

alter database 數據庫名 CHARACTER SET utf8;

定義兩個模型類:做者和書名:session

from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

#設置鏈接數據庫 root是用戶名 冒號後面是密碼
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/flasksql"

app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

#實例化SQLAlchemy對象,對誰操做
db = SQLAlchemy(app)
#定義模型類-做者
class Author(db.Model):
    #設置表名:author
    __tablename__ = "authors"
    #設置 id列
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(32),unique=True)
    #一對多,因此在一的地方聲明關係,與哪張表,backref爲類Author申明新屬性的方法
    au_book = db.relationship("Book",backref="author")
    def __repr__(self):
        return "Author:%s"%self.name

#定義模型類-書名 多對一
class Book(db.Model):
    __tablename__ = "books"
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(32))
    #關聯那個外鍵表,多對一 首先外鍵對應的是 模型類小寫點屬性
    au_book = db.Column(db.Integer,db.ForeignKey("author.id"))
    def __repr__(self):
        return "Book:%s,%s"%(self.name,self.id)

 

建立表

#建立表
if __name__ == '__main__':
    #建表以前須要將數據庫中的表清除完
    db.drop_all()
    db.create_all()
    app.run(debug=True)
    
    

查看錶成功建立。app

添加數據測試一下:函數

#生成數據
au1 = Author(name='老王')
au2 = Author(name='老尹')
au3 = Author(name='老劉')
# 把數據提交給用戶會話
db.session.add_all([au1, au2, au3])
# 提交會話
db.session.commit()
bk1 = Book(name='老王回憶錄', au_book=au1.id)
bk2 = Book(name='我讀書少,你別騙我', au_book=au1.id)
bk3 = Book(name='如何才能讓本身更騷', au_book=au2.id)
bk4 = Book(name='怎樣征服美麗少女', au_book=au3.id)
bk5 = Book(name='如何征服英俊少男', au_book=au3.id)
# 把數據提交給用戶會話
db.session.add_all([bk1, bk2, bk3, bk4, bk5])
# 提交會話
db.session.commit()

數據顯示&表單添加

定義路由函數,並將Author和Book的全部結果傳到模板post

@app.route('/',methods=['GET','POST'])
def index():
    author = Author.query.all()
    book = Book.query.all()
    return render_template('index.html',author=author,book=book)

模板:測試

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {% for x in author %}
    <li>{{ x }}</li>
    {% endfor %}
</ul>
<hr>
<ul>
    {% for x in book %}
    <li>{{ x }}</li>
    {% endfor %}
</ul>
</body>
</html>

表單添加  

  定義表單類

from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField,SubmitField
#建立表單類,用來添加信息
class Append(FlaskForm):
    au_info = StringField(validators=[DataRequired()])
    bk_info = StringField(validators=[DataRequired()])
    submit = SubmitField('添加')

傳入模板中:

@app.route('/',methods=['GET','POST'])
def index():
    author = Author.query.all()
    book = Book.query.all()
    form = Append()
    return render_template('index.html',author=author,book=book,form=form)

模板中的代碼;

<form method="post">
    {{ form.csrf_token }}
    <p>做者:{{ form.au_info }}</p>
    <p>書名:{{ form.bk_info }}</p>
    <p>{{ form.submit }}</p>
</form>

表單驗證

from flask import Flask,render_template,redirect,url_for,flash,request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField,SubmitField

app = Flask(__name__)
#設置密鑰
app.config["SECRET_KEY"] = "SECRET_KEY"

#設置鏈接數據庫
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:@127.0.0.1:3306/flasksql"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

#查詢時會顯示原始SQL
app.config["SQLALCHEMY_ECHO"] = True

#實例化SQLAlchemy對象,對誰操做
db = SQLAlchemy(app)
#定義模型類-做者
class Author(db.Model):
    #設置表名:author
    __tablename__ = "authors"
    #設置 id列
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(32),unique=True)
    #一對多,因此在一的地方聲明關係,與哪張表,backref爲類Author申明新屬性的方法
    us = db.relationship("Book",backref="author")
    def __repr__(self):
        return "Author:%s"%self.name

#定義模型類-書名 多對一
class Book(db.Model):
    __tablename__ = "books"
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(32))
    #關聯那個外鍵表,多對一 首先外鍵對應的是 建立的表名點屬性
    au_book = db.Column(db.Integer,db.ForeignKey("authors.id"))
    def __repr__(self):
        return "Book:%s,%s"%(self.name,self.id)
#建立表單類,用來添加信息
class Append(FlaskForm):
    au_info = StringField(validators=[DataRequired()])
    bk_info = StringField(validators=[DataRequired()])
    #這裏添加u才使得這個數據完整
    submit = SubmitField(u'添加')
# @app.route('/',methods=['GET','POST'])
# def index():
#     author = Author.query.all()
#     book = Book.query.all()
#     return render_template('index.html',author=author,book=book)
#
@app.route('/', methods=['get', 'post'])
def index():
    append_form = Append()

    if request.method == 'POST':
        if append_form.validate_on_submit():
            #先肯定值
            author_name = append_form.au_info.data
            book_name = append_form.bk_info.data
            # 判斷數據是否存在
            author = Author.query.filter_by(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, au_book=author.id)
                    db.session.add(book)
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    print(e)
                    flash("數據添加錯誤")
            else:
                #查詢和這個做者相關的書名
                book_names = [book.name for book in author.us]
                if book_name in book_names:
                    flash('該做者已存在相同的書名')
                else:
                    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:
            flash('數據輸入有問題')

    authors = Author.query.all()
    books = Book.query.all()
    return render_template('test2.html', authors=authors, books=books, append_form=append_form)






#生成數據
# au1 = Author(name='老大')
# au2 = Author(name='老二')
# au3 = Author(name='老三')
# # 把數據提交給用戶會話
# db.session.add_all([au1, au2, au3])
# # 提交會話
# db.session.commit()
# bk1 = Book(name='老王回憶錄', au_book=au1.id)
# bk2 = Book(name='我讀書少,你別騙我', au_book=au1.id)
# bk3 = Book(name='如何才能讓本身更騷', au_book=au2.id)
# bk4 = Book(name='怎樣征服美麗少女', au_book=au3.id)
# bk5 = Book(name='如何征服英俊少男', au_book=au3.id)
# # 把數據提交給用戶會話
# db.session.add_all([bk1, bk2, bk3, bk4, bk5])
# # 提交會話
# db.session.commit()
#建立表
if __name__ == '__main__':
    #建表以前須要將數據庫中的表清除完
    # db.drop_all()
    # db.create_all()
    app.run(debug=True,port=8080)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# 從新編寫html文件展現列表書籍 #}
<h2>書籍列表</h2>
<ul>
{% for author in authors %}
    <li>
        {{ author.name }}
        <ul>
            {% for book in author.us %}
                <li>{{ book.name }}
            {% else %}
                    <li>無書籍</li>
            {% endfor %}
        </ul>

    </li>
{% endfor %}
</ul>
<form method="post">
    {{ append_form.csrf_token }}
    <p>做者:{{ append_form.au_info }}</p>
    <p>書名:{{ append_form.bk_info }}</p>
    <p>{{ append_form.submit }}</p>
</form>
{# 在form標籤下添加 flash 消息的顯示 #}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</body>
</html>

 

 在form標籤下添加flash消息顯示

{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}

刪除數據

定義刪除author和book的路由

# 刪除做者
@app.route('/delete_author/<int:author_id>')
def delete_author(author_id):
    author = Author.query.get(author_id)
    if not author:
        flash('數據不存在')
    else:
        try:
        #要先刪除這個做者的書籍,再刪除做者 Book.query.filter_by(author_id
=author_id).delete() #刪除做者
       db.session.delete(author) db.session.commit()
except Exception as e: db.session.rollback() print(e) flash('操做數據庫失敗') return redirect(url_for('index')) # 刪除書籍 @app.route('/delete_book/<int:book_id>') def delete_book(book_id): book = Book.query.get(book_id) if not book: flash('數據不存在') else: try: db.session.delete(book) db.session.commit() except Exception as e: db.session.rollback() print(e) flash('操做數據庫失敗') return redirect(url_for('index'))

在模板中添加刪除的a標籤連接:

<h2>書籍列表</h2>
<ul>
{% for author in authors %}
    <li>
        {{ author.name }} <a href="/delete_author/{{ author.id }}">刪除</a>
        <ul>
            {% for book in author.books %}
                <li>{{ book.name }} <a href="/delete_book/{{ book.id }}">刪除</a></li>
            {% else %}
                    <li>無書籍</li>
            {% endfor %}
        </ul>

    </li>
{% endfor %}
</ul>
相關文章
相關標籤/搜索