我正在使用 sqlalchemy 的主/从,通过 RoutingSession 之类的
engines = {
'master':create_engine("sqlite:///master.db"),
'other':create_engine("sqlite:///other.db"),
'slave1':create_engine("sqlite:///slave1.db"),
'slave2':create_engine("sqlite:///slave2.db"),
}
from sqlalchemy.orm import Session, sessionmaker
import random
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None):
if mapper and issubclass(mapper.class_, MyOtherClass):
return engines['other']
elif self._flushing:
return engines['master']
else:
return engines[
random.choice(['slave1','slave2'])
]
http://docs.sqlalchemy.org/en/rel_0_7/orm/session.html#custom-vertical-partitioning
我在“get_bind”方法中打印了日志。我发现在使用“session.add(r); session.commit()”时,“get_bind”方法被执行了两次。那为什么要两次?
当使用“session.execute('insert ...'); session.commit()”时,“get_bind”方法只被调用一次。