gpt4 book ai didi

python - Flask Sqlalchemy中如何分离主从(DB读/写)

转载 作者:行者123 更新时间:2023-11-28 19:29:51 37 4
gpt4 key购买 nike

我正在尝试通过 Flask Sqlalchemy 分离读取和写入数据库操作。我正在使用绑定(bind)连接到 mysql 数据库。我想在 Master 中执行写操作并从 slave 中读取。似乎没有内置的方法来处理这个问题。

我是 python 的新手,很惊讶像这样急需的功能还没有预先内置到 flask-sqlalchemy 中。任何帮助表示赞赏。谢谢

最佳答案

没有官方支持,但是你可以自定义Flask-SQLalchemy session 来使用master slave connects

from functools import partial

from sqlalchemy import orm
from flask import current_app
from flask_sqlalchemy import SQLAlchemy, get_state


class RoutingSession(orm.Session):
def __init__(self, db, autocommit=False, autoflush=True, **options):
self.app = db.get_app()
self.db = db
self._bind_name = None
orm.Session.__init__(
self, autocommit=autocommit, autoflush=autoflush,
bind=db.engine,
binds=db.get_binds(self.app),
**options,
)

def get_bind(self, mapper=None, clause=None):
try:
state = get_state(self.app)
except (AssertionError, AttributeError, TypeError) as err:
current_app.logger.info(
'cant get configuration. default bind. Error:' + err)
return orm.Session.get_bind(self, mapper, clause)

# If there are no binds configured, use default SQLALCHEMY_DATABASE_URI
if not state or not self.app.config['SQLALCHEMY_BINDS']:
return orm.Session.get_bind(self, mapper, clause)

# if want to user exact bind
if self._bind_name:
return state.db.get_engine(self.app, bind=self._bind_name)
else:
# if no bind is used connect to default
return orm.Session.get_bind(self, mapper, clause)

def using_bind(self, name):
bind_session = RoutingSession(self.db)
vars(bind_session).update(vars(self))
bind_session._bind_name = name
return bind_session


class RouteSQLAlchemy(SQLAlchemy):
def __init__(self, *args, **kwargs):
SQLAlchemy.__init__(self, *args, **kwargs)
self.session.using_bind = lambda s: self.session().using_bind(s)

def create_scoped_session(self, options=None):
if options is None:
options = {}
scopefunc = options.pop('scopefunc', None)
return orm.scoped_session(
partial(RoutingSession, self, **options),
scopefunc=scopefunc,
)

默认 session 是master,当你想从slave中选择时你可以直接调用它,这里是例子:

在您的应用中:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///master'
app.config['SQLALCHEMY_BINDS'] = {
'slave': 'postgresql:///slave'
}

db = RouteSQLAlchemy(app)

从大师中选择

session.query(User).filter_by(id=1).first() 

从奴隶中选择

session.using_bind('slave').query(User).filter_by(id=1).first() 

关于python - Flask Sqlalchemy中如何分离主从(DB读/写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12093956/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com