Bootstrap

flask之flask-SQLAlchemy读写分离

读写分离

示范代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy, SignallingSession, get_state
from sqlalchemy import orm

app = Flask(__name__)
# 设置数据库的连接地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/demo'
app.config['SQLALCHEMY_BINDS'] = {
   
    'master': 'mysql://root:[email protected]:3306/demo',
    'slave': 'mysql://root:[email protected]:8306/demo'
}
# 设置是否追踪数据库变化
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 设置是否在控制台打印sql语句
app.config['SQLALCHEMY_ECHO'] = False

class RoutingSession(SignallingSession):
    def get_bind(self, mapper=None, clause=None):
        '''每次操作数据库时,会调用该方法获得访问数据库的地址'''

        # 根据读写选择相应的数据库地址
        state = get_state(self.app)
        if self._flushing: # 增删改操作,选择主数据库
            print('访问主库')
            return state.db.get_engine(self.app, bind='master')
        else: # 读操作,选择从数据库
            print('访问从库')
            return state.db.get_engine(self.app, bind='slave')

# 重写SQLAlchemy的create_session方法,使用我们自定义的RoutingSession
class RoutingSQLAlchemy(SQLAlchemy):
    def create_session(self, op
;