用python写数据库的主从怎么写_如何在Flask Sqlalchemy中分离主从(DB读/写)

本文介绍了如何在 Flask 应用中利用 SQLAlchemy 自定义 RoutingSession 类实现数据库主从分离。通过创建 RoutingSession,可以在需要时选择从主库或从库进行读取操作,提供了一种在应用中灵活切换读写数据库的方法。
摘要由CSDN通过智能技术生成

虽然没有官方支持,但是您可以定制Flask SQLalchemy会话来使用主从连接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,

)

而默认会话将是master,当您想从slave中选择时,可以直接调用它,下面是示例:

在你的应用程序中:

^{pr2}$

从主控形状中选择session.query(User).filter_by(id=1).first()

从从属服务器选择session.using_bind('slave').query(User).filter_by(id=1).first()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值