python - Why SQLAlchemy Session.filter().update/delete raise read-only exception when using RoutingSession? -
the following config, slave read-only:
engines = { 'master': create_engine( settings.master_url, echo=settings.echo_sql, pool_recycle=3600), 'slave': create_engine( settings.slave_url, echo=settings.echo_sql, pool_recycle=3600), } class routingsession(session): def get_bind(self, mapper=none, clause=none): #return engines['master'] if self._flushing: return engines['master'] else: return engines['slave'] dbsession = scoped_session(sessionmaker(class_=routingsession))
when :
s = dbsession() #synchronize_session=false makes execution faster s.query(model).filter(model.id == 1).delete(synchronize_session=false) s.commit()
it raises exception couldn't delete because of "read-only".
how rewrite routingsession make above 'delete' use 'master' database
---edit1---
i've done more test. above 'delete' different following 'delete' routingsession return 'master':
model = s.query(model).filter(model.id == 1).first() s.delete(model) s.commit()
a query.delete()
not part of "flush", typically if you're using routing session recipe, want implement using_bind()
, call upon before operation delete()
:
class routingsession(session): def get_bind(self, mapper=none, clause=none ): if self._name: return engines[self._name] else: # other cases here _name = none def using_bind(self, name): s = routingsession() vars(s).update(vars(self)) s._name = name return s
then use:
session().using_bind("master").query(model1).delete()
Comments
Post a Comment