Flask SQLAlchemy

在Flask Web應(yīng)用程序中使用原始SQL對(duì)數(shù)據(jù)庫(kù)執(zhí)行CRUD操作可能很乏味。 相反,Python工具包SQLAlchemy是一個(gè)功能強(qiáng)大的OR映射器,為應(yīng)用程序開發(fā)人員提供了SQL的全部功能和靈活性。 Flask-SQLAlchemy是Flask擴(kuò)展,它將對(duì)SQLAlchemy的支持添加到Flask應(yīng)用程序中。

什么是ORM(對(duì)象關(guān)系映射)?

大多數(shù)編程語(yǔ)言平臺(tái)是面向?qū)ο蟮摹?另一方面,RDBMS服務(wù)器中的數(shù)據(jù)以表格形式存儲(chǔ)。 對(duì)象關(guān)系映射是一種將對(duì)象參數(shù)映射到底層RDBMS表結(jié)構(gòu)的技術(shù)。 ORM API提供了執(zhí)行CRUD操作的方法,而無(wú)需編寫原始SQL語(yǔ)句。

在本節(jié)中,我們將學(xué)習(xí)使用Flask-SQLAlchemy的ORM技術(shù)并構(gòu)建一個(gè)小型Web應(yīng)用程序。

第1步 - 安裝Flask-SQLAlchemy擴(kuò)展。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
pip install flask-sqlalchemy

第2步 - 需要從該模塊導(dǎo)入SQLAlchemy類。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
from flask_sqlalchemy import SQLAlchemy

第3步 - 現(xiàn)在創(chuàng)建一個(gè)Flask應(yīng)用程序?qū)ο蟛橐褂玫臄?shù)據(jù)庫(kù)設(shè)置URI。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
app = Flask(__name__)
 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'

第4步 - 然后用應(yīng)用程序?qū)ο笞鳛閰?shù)創(chuàng)建一個(gè)SQLAlchemy類的對(duì)象。 該對(duì)象包含ORM操作的輔助函數(shù)。 它還提供了一個(gè)使用其聲明用戶定義模型的父級(jí)模型類。 在下面的代碼片段中,創(chuàng)建了一個(gè)學(xué)生模型。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
db = SQLAlchemy(app)
 class students(db.Model):
     id = db.Column('student_id', db.Integer, primary_key = True)
     name = db.Column(db.String(100))
     city = db.Column(db.String(50)) 
     addr = db.Column(db.String(200))
     pin = db.Column(db.String(10))
 def __init__(self, name, city, addr,pin):
     self.name = name
     self.city = city
     self.addr = addr
     self.pin = pin

第5步 - 要?jiǎng)?chuàng)建/使用URI中提到的數(shù)據(jù)庫(kù),請(qǐng)運(yùn)行create_all()方法。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
db.create_all()

SQLAlchemy的Session對(duì)象管理ORM對(duì)象的所有持久性操作。

以下會(huì)話方法執(zhí)行CRUD操作 -

db.session.add(模型對(duì)象) - 將一條記錄插入到映射表中 db.session.delete(模型對(duì)象) - 從表中刪除記錄 model.query.all() - 從表中檢索所有記錄(對(duì)應(yīng)于SELECT查詢)。

可以使用filter屬性將篩選器應(yīng)用于檢索到的記錄集。例如,要在students表中檢索city ='Haikou'的記錄,請(qǐng)使用以下語(yǔ)句 -

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
Students.query.filter_by(city = 'Haikou').all()

有了這么多的背景知識(shí),現(xiàn)在我們將為我們的應(yīng)用程序提供視圖函數(shù)來(lái)添加學(xué)生數(shù)據(jù)。

應(yīng)用程序的入口點(diǎn)是綁定到URL => ‘/‘的show_all()函數(shù)。學(xué)生的記錄集作為參數(shù)發(fā)送給HTML模板。 模板中的服務(wù)器端代碼以HTML表格形式呈現(xiàn)記錄。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
@app.route('/')
 def show_all():
     return render_template('show_all.html', students = students.query.all() )

模板的HTML腳本( show_all.html)就像這樣 -

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
       <h3>
          <a href = "{{ url_for('show_all') }}">學(xué)生列表 - Flask 
             SQLAlchemy示例</a>
       </h3>
       <hr/>
       {%- for message in get_flashed_messages() %}
          {{ message }}
       {%- endfor %}
       <h3>學(xué)生 (<a href = "{{ url_for('new') }}">添加
          </a>)</h3>
       <table>
          <thead>
             <tr>
                <th>姓名</th>
                <th>城市</th>
                <th>地址</th>
                <th>Pin</th>
             </tr>
          </thead>
          <tbody>
             {% for student in students %}
                <tr>
                   <td>{{ student.name }}</td>
                   <td>{{ student.city }}</td>
                   <td>{{ student.addr }}</td>
                   <td>{{ student.pin }}</td>
                </tr>
             {% endfor %}
          </tbody>
       </table>
    </body>
 </html>

上面的頁(yè)面包含一個(gè)指向URL:/new 映射new()函數(shù)的超鏈接。點(diǎn)擊后,它會(huì)打開一個(gè)學(xué)生信息表單。 數(shù)據(jù)在POST方法中發(fā)布到相同的URL。

模板文件: new.html 的代碼如下 -

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
     <h3>學(xué)生信息 - Flask SQLAlchemy示例</h3>
       <hr/>
       {%- for category, message in get_flashed_messages(with_categories = True) %}
          <div class = "alert alert-danger">
             {{ message }}
          </div>
       {%- endfor %}
       <form action = "{{ request.path }}" method = "post">
          <label for = "name">姓名</label><br>
          <input type = "text" name = "name" placeholder = "Name" /><br>
          <label for = "email">城市</label><br>
          <input type = "text" name = "city" placeholder = "city" /><br>
          <label for = "addr">地址</label><br>
          <textarea name = "addr" placeholder = "addr"/><br>
          <label for = "PIN">城市</label><br>
          <input type = "text" name = "pin" placeholder = "pin" /><br>
          <input type = "submit" value = "提交" />
       </form>
    </body>
 </html>

當(dāng)檢測(cè)到http方法為POST時(shí),表單數(shù)據(jù)將插入到students表中,并且應(yīng)用程序返回到顯示數(shù)據(jù)的主頁(yè)。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
@app.route('/new', methods = ['GET', 'POST'])
 def new():
     if request.method == 'POST':
        if not request.form['name'] or not request.form['city'] or not request.form['addr']:
          flash('Please enter all the fields', 'error')
        else:
           student = students(request.form['name'], request.form['city'],
              request.form['addr'], request.form['pin'])
           db.session.add(student)
           db.session.commit()
           flash('Record was successfully added')
           return redirect(url_for('show_all'))
     return render_template('new.html')

下面給出的是完整的應(yīng)用程序代碼( app.py)。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
from flask import Flask, request, flash, url_for, redirect, render_template
 from flask_sqlalchemy import SQLAlchemy
 app = Flask(__name__)
 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
 app.config['SECRET_KEY'] = "random string"
 db = SQLAlchemy(app)
 class students(db.Model):
     id = db.Column('student_id', db.Integer, primary_key = True)
     name = db.Column(db.String(100))
     city = db.Column(db.String(50))
     addr = db.Column(db.String(200)) 
     pin = db.Column(db.String(10))
     def __init__(self, name, city, addr,pin):
         self.name = name
         self.city = city
         self.addr = addr
         self.pin = pin
 @app.route('/')
 def show_all():
     return render_template('show_all.html', students = students.query.all() )
 @app.route('/new', methods = ['GET', 'POST'])
 def new():
     if request.method == 'POST':
        if not request.form['name'] or not request.form['city'] or not request.form['addr']:
           flash('Please enter all the fields', 'error')
        else:
           student = students(request.form['name'], request.form['city'],request.form['addr'], request.form['pin'])
           print(student)
           db.session.add(student)
           db.session.commit()
           flash('Record was successfully added')
           return redirect(url_for('show_all'))
     return render_template('new.html')
 if __name__ == '__main__':
     db.create_all()
     app.run(debug = True)

從Python shell運(yùn)行腳本,并在瀏覽器中輸入:http://localhost:5000/ ,顯示結(jié)果如下 -

Python shell運(yùn)行腳本

點(diǎn)擊“ 添加”鏈接打開學(xué)生信息表單。

鏈接打開學(xué)生信息表單

填寫表單并提交,主頁(yè)將提交的數(shù)據(jù)列出來(lái)。操作之后,將看到如下所示的輸出。

顯示表單數(shù)據(jù)

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清