聊聊Flask使用SQLite數(shù)據(jù)庫(kù),你會(huì)嗎?
SQLite是一個(gè)小型的輕量數(shù)據(jù)庫(kù),特別適合個(gè)人學(xué)習(xí)使用。因?yàn)镾QLite不需要額外的數(shù)據(jù)庫(kù)服務(wù)器,同時(shí)它也是內(nèi)嵌在Python中的。缺點(diǎn)就是如果有大量的寫請(qǐng)求過(guò)來(lái),它是串行處理的,速度很慢。
連接數(shù)據(jù)庫(kù)
新建flaskr/db.py文件:
- import sqlite3
- import click
- from flask import current_app, g
- from flask.cli import with_appcontext
- def get_db():
- if 'db' not in g:
- g.db = sqlite3.connect(
- current_app.config['DATABASE'],
- detect_types=sqlite3.PARSE_DECLTYPES
- )
- g.db.row_factory = sqlite3.Row
- return g.db
- def close_db(e=None):
- db = g.pop('db', None)
- if db is not None:
- db.close()
g是flask給每個(gè)請(qǐng)求創(chuàng)建的獨(dú)立的對(duì)象,用來(lái)存儲(chǔ)全局?jǐn)?shù)據(jù)。通過(guò)g實(shí)現(xiàn)了同一個(gè)請(qǐng)求多次調(diào)用get_db時(shí),不會(huì)創(chuàng)建新連接而是會(huì)復(fù)用已建立的連接。
get_db會(huì)在flask應(yīng)用創(chuàng)建后,處理數(shù)據(jù)庫(kù)連接時(shí)被調(diào)用。
sqlite3.connect()用來(lái)建立數(shù)據(jù)庫(kù)連接,它指定了配置文件的Key DATABASE。
sqlite3.Row讓數(shù)據(jù)庫(kù)以字典的形式返回行,這樣就能通過(guò)列名進(jìn)行取值。
close_db關(guān)閉數(shù)據(jù)庫(kù)連接,它先檢查g.db有沒(méi)有設(shè)置,如果設(shè)置了就關(guān)閉db。
創(chuàng)建表
新建flaskr/schema.sql文件:
- DROP TABLE IF EXISTS user;
- DROP TABLE IF EXISTS post;
- CREATE TABLE user (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- username TEXT UNIQUE NOT NULL,
- password TEXT NOT NULL
- );
- CREATE TABLE post (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- author_id INTEGER NOT NULL,
- created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- title TEXT NOT NULL,
- body TEXT NOT NULL,
- FOREIGN KEY (author_id) REFERENCES user (id)
- );
在flaskr/db.py文件中添加以下代碼:
- def init_db():
- db = get_db()
- with current_app.open_resource('schema.sql') as f:
- db.executescript(f.read().decode('utf8'))
- @click.command('init-db')
- @with_appcontext
- def init_db_command():
- """Clear the existing data and create new tables."""
- init_db()
- click.echo('Initialized the database.')
open_resource()打開剛才創(chuàng)建的數(shù)據(jù)庫(kù)腳本文件。
@click.command()定義了命令行命令init-db。
注冊(cè)到應(yīng)用
close_db和init_db_command函數(shù)Flask不會(huì)自動(dòng)觸發(fā),需要手動(dòng)注冊(cè)到應(yīng)用上。
編輯flaskr/db.py文件:
- def init_app(app):
- app.teardown_appcontext(close_db)
- app.cli.add_command(init_db_command)
app.teardown_appcontext指定響應(yīng)結(jié)束后清理時(shí)的函數(shù)。
app.cli.add_command定義了可以被flask命令使用的命令。
再把init_app手動(dòng)添加到創(chuàng)建應(yīng)用函數(shù)中,編輯flaskr/__init__.py文件:
- def create_app():
- app = ...
- # existing code omitted
- from . import db
- db.init_app(app)
- return app
執(zhí)行命令
至此,準(zhǔn)備工作已就緒,打開命令行執(zhí)行:
- $ flask init-db
- Initialized the database.
在項(xiàng)目目錄下,就會(huì)生成一個(gè)flaskr.sqlite,這就是SQLite數(shù)據(jù)庫(kù)。
參考資料:
https://flask.palletsprojects.com/en/2.0.x/tutorial/database/