How to do 'if else' judgement in SQLAlchemy RoutingSession.get_bind when using with_lockmode(master query)
-
04-07-2021 - |
Domanda
I want to get a row from mysql database, then modiy some fields and commit. Before I commit, updating this row shoud be forbidden. so I use with_lockmode('update'). I use the following RoutingSession and I find it use Slave to do this query. But I want to do this query using Master, what should I do in 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()
Soluzione
I'm assuming you got this recipe from my blog post at Django-style Database Routers in SQLAlchemy. If you look in the section "manual access" you'll see a recipe for when you need to explicitly point the routing session to a certain node:
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
Then you just do your operation with that bind explicitly:
m1 = Session().using_bind("master").query(Model1).first()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow