读写分离
示范代码
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
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')
class RoutingSQLAlchemy(SQLAlchemy):
def create_session(self, op