我想从mysql数据库中获得一行,然后修改一些字段并提交。在我提交之前,应该禁止更新这一行。所以我使用with_lockmode('update').我使用下面的RoutingSession,并发现它使用从来执行这个查询。但是我想使用主进行这个查询,我应该在get_bind中做什么?
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None):
if self._flushing:
return engines['master']
else:
return engines['slave']
row = session.query(SomeTable).filter(SomeTable.id = 1).with_lockmode('update').one
row.somefield = 'newcontent'
session.commit()发布于 2012-10-04 15:07:20
我想你是从我在SQLAlchemy中的Django型数据库路由器的博文中得到这个食谱的。如果您查看“手动访问”一节,您将看到需要将路由会话显式地指向某个节点的方法:
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None ):
if self._name:
return engines[self._name]
elif mapper and issubclass(mapper.class_, OtherBase):
return engines['other']
elif self._flushing:
return engines['master']
else:
return engines[
random.choice(['slave1','slave2'])
]
_name = None
def using_bind(self, name):
s = RoutingSession()
vars(s).update(vars(self))
s._name = name
return s然后,您只需显式地使用该绑定执行操作:
m1 = Session().using_bind("master").query(Model1).first()https://stackoverflow.com/questions/12619041
复制相似问题