Flask SQLAlchemy


在Flask Web應用程式中使用原始SQL對資料庫執行CRUD操作可能很乏味。 相反,Python工具包SQLAlchemy是一個功能強大的OR對映器,為應用程式開發人員提供了SQL的全部功能和靈活性。 Flask-SQLAlchemy是Flask擴充套件,它將對SQLAlchemy的支援新增到Flask應用程式中。

什麼是ORM(物件關係對映)?

大多數程式設計語言平台是物件導向的。 另一方面,RDBMS伺服器中的資料以表格形式儲存。 物件關係對映是一種將物件引數對映到底層RDBMS表結構的技術。 ORM API提供了執行CRUD操作的方法,而無需編寫原始SQL語句。

在本節中,我們將學習使用Flask-SQLAlchemy的ORM技術並構建一個小型Web應用程式。

第1步 - 安裝Flask-SQLAlchemy擴充套件。

pip install flask-sqlalchemy

第2步 - 需要從該模組匯入SQLAlchemy類。

from flask_sqlalchemy import SQLAlchemy

第3步 - 現在建立一個Flask應用程式物件並為要使用的資料庫設定URI。

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'

第4步 - 然後用應用程式物件作為引數建立一個SQLAlchemy類的物件。 該物件包含ORM操作的輔助函式。 它還提供了一個使用其宣告使用者定義模型的父級模型類。 在下面的程式碼片段中,建立了一個學生模型。

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步 - 要建立/使用URI中提到的資料庫,請執行create_all()方法。

db.create_all()

SQLAlchemy的Session物件管理ORM物件的所有永續性操作。

以下對談方法執行CRUD操作 -

  • db.session.add(模型物件) - 將一條記錄插入到對映表中
  • db.session.delete(模型物件) - 從表中刪除記錄
  • model.query.all() - 從表中檢索所有記錄(對應於SELECT查詢)。

可以使用filter屬性將篩選器應用於檢索到的記錄集。例如,要在students表中檢索city ='Haikou'的記錄,請使用以下語句 -

Students.query.filter_by(city = 'Haikou').all()

有了這麼多的背景知識,現在我們將為我們的應用程式提供檢視函式來新增學生資料。

應用程式的入口點是系結到URL => ‘/‘的show_all()函式。學生的記錄集作為引數傳送給HTML模板。 模板中的伺服器端程式碼以HTML表格形式呈現記錄。

@app.route('/')
def show_all():
    return render_template('show_all.html', students = students.query.all() )

模板的HTML指令碼(show_all.html)就像這樣 -

<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') }}">學生列表 - Flask 
            SQLAlchemy範例</a>
      </h3>

      <hr/>
      {%- for message in get_flashed_messages() %}
         {{ message }}
      {%- endfor %}

      <h3>學生 (<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>

上面的頁面包含一個指向URL:/new 對映new()函式的超連結。點選後,它會開啟一個學生資訊表單。 資料在POST方法中發布到相同的URL。

模板檔案:new.html 的程式碼如下 -

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask範例</title>
</head>
   <body>
    <h3>學生資訊 - 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>

當檢測到http方法為POST時,表單資料將插入到students表中,並且應用程式返回到顯示資料的主頁。

@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')

下面給出的是完整的應用程式程式碼(app.py)。

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執行指令碼,並在瀏覽器中輸入:http://localhost:5000/ ,顯示結果如下 -

點選「新增」連結開啟學生資訊表單。

填寫表單並提交,主頁將提交的資料列出來。操作之後,將看到如下所示的輸出。