今天整理一下flask-sqlalchemy對數據庫的操作, 基礎代碼如下
cat flaskStudy.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqllist')
db = SQLAlchemy(app)
class Role(db.Model):
__tablename__ = 'roles'
users = db.relationship('User', backref='role') # roles表與users表一對多的映射關系
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
def __repr__(self):
return "<Role %r>" % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) # role_id 的值根據偽列role的值(指向roles對象)自動生成
username = db.Column(db.String(64), unique=True, index=True)
def __repr__(self):
return "<User %r>" % self.username
if __name__ == '__main__':
app.run()
兩張表:roles, users, 一對多關系
1、數據插入
(venv) D:\flaskStudy>set FLASK_APP=flaskStudy.py (venv) D:\flaskStudy>set FLASK_DEBUG=1 (venv) D:\flaskStudy>flask shell Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32 App: flaskStudy [production] Instance: D:\flaskStudy\instance >>> from flaskStudy import db, Role, User >>> db.drop_all() # 刪除所有表 >>> db.create_all() # 創建所有表 >>> admin_role=Role(name='Admin') # 創建角色對象 >>> mod_role=Role(name='Moderator') >>> user_role=Role(name='User') >>> user_john=User(username='John', role=admin_role) # 創建用戶對象, 根據role對象動態生成role_id >>> user_susan=User(username='susan', role=user_role) >>> user_david=User(username='david', role=user_role) >>> db.session.add(admin_role) >>> db.session.add(mod_role) >>> db.session.add(user_role) >>> db.session.add(user_john) >>> db.session.add(user_susan) >>> db.session.add(user_david) >>> db.session.commit()
2、數據查詢
(venv) D:\flaskStudy>flask shell Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32 App: flaskStudy [production] Instance: D:\flaskStudy\instance >>> from flaskStudy import db, User, Role >>> user_role=Role.query.filter_by(name='User').first() # 查詢一條roles數據 >>> user_role <Role 'User'> >>> user_role.users # 根據users列正向查詢users表對應的用戶 [<User 'susan'>, <User 'david'>] >>> user_david=User.query.filter_by(username='david').first() # 查詢一條用戶數據 >>> user_david <User 'david'> >>> user_david.role # 根據偽列role查詢對應的角色 <Role 'User'> >>>
3、數據修改
(venv) D:\flaskStudy>flask shell Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32 App: flaskStudy [production] Instance: D:\flaskStudy\instance >>> from flaskStudy import db, User, Role >>> Role.query.all() # roles表有三條數據 [<Role 'Admin'>, <Role 'Moderator'>, <Role 'User'>] >>> admin_role=Role.query.filter_by(name='Admin').first() # 查詢其中一條數據 >>> admin_role <Role 'Admin'> >>> admin_role.name='Administrator' # 將name值修改為Administrator >>> db.session.add(admin_role) >>> db.session.commit() >>> Role.query.all() [<Role 'Administrator'>, <Role 'Moderator'>, <Role 'User'>]
4、刪除數據
>>> Role.query.all() # 角色中三條記錄 [<Role 'Administrator'>, <Role 'Moderator'>, <Role 'User'>] >>> user_role=Role.query.filter_by(name='User').first() # 其中一條數據對象 >>> user_role <Role 'User'> >>> db.session.delete(user_role) # 刪除此對象 >>> db.session.commit() >>> Role.query.all() [<Role 'Administrator'>, <Role 'Moderator'>] >>> User.query.all() # users表中后兩條數據的role_id沒有了依賴被置空 [<User 'John'>, <User 'susan'>, <User 'david'>]
5、集成Python shell
每次啟動flask shell會話都要手動導入數據庫實例和模型才能進行數據庫操作, 當啟動flask shell時如何實現自動導入呢?
shell_context_processor: 注冊並創建一個shell上下文處理器。
@app.shell_context_processor # 注冊並創建shell上下文處理器
def make_shell_context():
return dict(db=db, User=User, Role=Role) # 返回包含實例和模型的字典
再次運行flask shell, 這些實例和模型都可以使用了
(venv) D:\flaskStudy>flask shell
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
App: flaskStudy [production]
Instance: D:\flaskStudy\instance
>>> db
<SQLAlchemy engine=sqlite:///D:\flaskStudy\data.sqllist>
>>> app
<Flask 'flaskStudy'>
>>> User
<class 'flaskStudy.User'>
>>> Role
<class 'flaskStudy.Role'>
6、創建遷移倉庫
項目遷移后, 數據庫同樣需要遷移
from flask_migrate import Migrate migrate = Migrate(app, db)
db init子命令添加添加數據庫遷移支持, 此時自動創建目錄存儲數據

