Flask SQLite

2022-03-10 16:34 更新

在 Flask 中,通過使用特殊的 g 對(duì)象可以使用 before_request() 和 teardown_request() 在請(qǐng)求開始前打開數(shù)據(jù)庫連接,在請(qǐng)求結(jié)束后關(guān)閉連接。

以下是一個(gè)在 Flask 中使用 SQLite 3 的例子:

import sqlite3
from flask import g

DATABASE = '/path/to/database.db'

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()
請(qǐng)記住,銷毀函數(shù)是一定會(huì)被執(zhí)行的。即使請(qǐng)求前處理器執(zhí)行失敗或根本沒有執(zhí)行, 銷毀函數(shù)也會(huì)被執(zhí)行。因此,我們必須保證在關(guān)閉數(shù)據(jù)庫連接之前數(shù)據(jù)庫連接是存在 的。

按需連接

上述方式的缺點(diǎn)是只有在 Flask 執(zhí)行了請(qǐng)求前處理器時(shí)才有效。如果你嘗試在腳本或者 Python 解釋器中使用數(shù)據(jù)庫,那么你必須這樣來執(zhí)行數(shù)據(jù)庫連接代碼:

with app.test_request_context():
    app.preprocess_request()
    # now you can use the g.db object

這樣雖然不能排除對(duì)請(qǐng)求環(huán)境的依賴,但是可以按需連接數(shù)據(jù)庫:

def get_connection():
    db = getattr(g, '_db', None)
    if db is None:
        db = g._db = connect_db()
    return db

這樣做的缺點(diǎn)是必須使用 db = get_connection() 來代替直接使用 g.db 。

簡(jiǎn)化查詢

現(xiàn)在,在每個(gè)請(qǐng)求處理函數(shù)中可以通過訪問 g.db 來得到當(dāng)前打開的數(shù)據(jù)庫連接。為了 簡(jiǎn)化 SQLite 的使用,這里有一個(gè)有用的輔助函數(shù):

def query_db(query, args=(), one=False):
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

使用這個(gè)實(shí)用的小函數(shù)比直接使用原始指針和轉(zhuǎn)接對(duì)象要舒服一點(diǎn)。

可以這樣使用上述函數(shù):

for user in query_db('select * from users'):
    print user['username'], 'has the id', user['user_id']

只需要得到單一結(jié)果的用法:

user = query_db('select * from users where username = ?',
                [the_username], one=True)
if user is None:
    print 'No such user'
else:
    print the_username, 'has the id', user['user_id']

如果要給 SQL 語句傳遞參數(shù),請(qǐng)?jiān)谡Z句中使用問號(hào)來代替參數(shù),并把參數(shù)放在一個(gè)列表中 一起傳遞。不要用字符串格式化的方式直接把參數(shù)加入 SQL 語句中,這樣會(huì)給應(yīng)用帶來 SQL 注入 的風(fēng)險(xiǎn)。

初始化模式

關(guān)系數(shù)據(jù)庫是需要模式的,因此一個(gè)應(yīng)用常常需要一個(gè) schema.sql 文件來創(chuàng)建 數(shù)據(jù)庫。因此我們需要使用一個(gè)函數(shù)來其于模式創(chuàng)建數(shù)據(jù)庫。下面這個(gè)函數(shù)可以完成這個(gè) 任務(wù):

from contextlib import closing

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()

可以使用上述函數(shù)在 Python 解釋器中創(chuàng)建數(shù)據(jù)庫:

>>> from yourapplication import init_db
>>> init_db()


以下是一個(gè)實(shí)例:

創(chuàng)建一個(gè)SQLite數(shù)據(jù)庫'database.db'并在其中創(chuàng)建學(xué)生表。

import sqlite3

conn = sqlite3.connect('database.db')
print "Opened database successfully";

conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print "Table created successfully";
conn.close()

我們的Flask應(yīng)用程序有三個(gè)View功能。

第一個(gè)new_student()函數(shù)已綁定到URL規(guī)則('/addnew')。它呈現(xiàn)包含學(xué)生信息表單的HTML文件。

@app.route('/enternew')
def new_student():
   return render_template('student.html')

'student.html'的HTML腳本如下:

<html>
   <body>
      <form action = "{{ url_for('addrec') }}" method = "POST">
         <h3>Student Information</h3>
         Name<br>
         <input type = "text" name = "nm" /></br>
         Address<br>
         <textarea name = "add" ></textarea><br>
         City<br>
         <input type = "text" name = "city" /><br>
         PINCODE<br>
         <input type = "text" name = "pin" /><br>
         <input type = "submit" value = "submit" /><br>
      </form>
   </body>
</html>

可以看出,表單數(shù)據(jù)被發(fā)布到綁定addrec()函數(shù)的'/addrec' URL。

這個(gè)addrec()函數(shù)通過POST方法檢索表單的數(shù)據(jù),并插入學(xué)生表中。與insert操作中的成功或錯(cuò)誤相對(duì)應(yīng)的消息將呈現(xiàn)為'result.html'

@app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
      try:
         nm = request.form['nm']
         addr = request.form['add']
         city = request.form['city']
         pin = request.form['pin']
         
         with sql.connect("database.db") as con:
            cur = con.cursor()
            cur.execute("INSERT INTO students (name,addr,city,pin) 
               VALUES (?,?,?,?)",(nm,addr,city,pin) )
            
            con.commit()
            msg = "Record successfully added"
      except:
         con.rollback()
         msg = "error in insert operation"
      
      finally:
         return render_template("result.html",msg = msg)
         con.close()

result.html的HTML腳本包含一個(gè)轉(zhuǎn)義語句{{msg}},它顯示Insert操作的結(jié)果。

<!doctype html>
<html>
   <body>
   
      result of addition : {{ msg }}
      <h2><a href = "\">go back to home page</a></h2>
      
   </body>
</html>

該應(yīng)用程序包含由'/list' URL表示的另一個(gè)list()函數(shù)。

它將'rows'填充為包含學(xué)生表中所有記錄的MultiDict對(duì)象。此對(duì)象將傳遞給list.html模板。

@app.route('/list')
def list():
   con = sql.connect("database.db")
   con.row_factory = sql.Row
   
   cur = con.cursor()
   cur.execute("select * from students")
   
   rows = cur.fetchall()
   return render_template("list.html",rows = rows)

list.html是一個(gè)模板,它遍歷行集并在HTML表中呈現(xiàn)數(shù)據(jù)。

<!doctype html>
<html>
   <body>
   
      <table border = 1>
         <thead>
            <td>Name</td>
            <td>Address</td>
            <td>city</td>
            <td>Pincode</td>
         </thead>
         
         {% for row in rows %}
            <tr>
               <td>{{row["name"]}}</td>
               <td>{{row["addr"]}}</td>
               <td> {{ row["city"]}}</td>
               <td>{{row['pin']}}</td>	
            </tr>
         {% endfor %}
      </table>
      
      <a href = "/">Go back to home page</a>
      
   </body>
</html>

最后,'/' URL規(guī)則呈現(xiàn)'home.html',它作為應(yīng)用程序的入口點(diǎn)。

@app.route('/')
def home():
   return render_template('home.html')

home.html的頁面比較簡(jiǎn)單,只需要負(fù)責(zé)相關(guān)的頁面跳轉(zhuǎn)即可:

<!DOCTYPE html>
<html>

<body>
    <a href="/enternew">Add New Record</a>
    <br />
    <a href="/list">Show List</a>
</body>
</html>

以下是Flask-SQLite應(yīng)用程序的完整代碼。

from flask import Flask, render_template, request
import sqlite3 as sql
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('home.html')

@app.route('/enternew')
def new_student():
   return render_template('student.html')

@app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
      try:
         nm = request.form['nm']
         addr = request.form['add']
         city = request.form['city']
         pin = request.form['pin']
         
         with sql.connect("database.db") as con:
            cur = con.cursor()
            
            cur.execute("INSERT INTO students (name,addr,city,pin) 
               VALUES (?,?,?,?)",(nm,addr,city,pin) )
            
            con.commit()
            msg = "Record successfully added"
      except:
         con.rollback()
         msg = "error in insert operation"
      
      finally:
         return render_template("result.html",msg = msg)
         con.close()

@app.route('/list')
def list():
   con = sql.connect("database.db")
   con.row_factory = sql.Row
   
   cur = con.cursor()
   cur.execute("select * from students")
   
   rows = cur.fetchall();
   return render_template("list.html",rows = rows)

if __name__ == '__main__':
   app.run(debug = True)

在開發(fā)服務(wù)器開始運(yùn)行時(shí),從Python shell運(yùn)行此腳本。在瀏覽器中訪問http://localhost:5000/,顯示一個(gè)簡(jiǎn)單的菜單:

Simple Menu

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

Adding New Record

填寫表單字段并提交。底層函數(shù)在學(xué)生表中插入記錄。

Record Successfully Added

返回首頁,然后點(diǎn)擊'顯示列表'鏈接。將顯示一個(gè)顯示樣品數(shù)據(jù)的表。

Table Showing Sample Data


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)