【发布时间】:2014-05-18 20:22:50
【问题描述】:
我有 2 个函数需要执行,第一个函数需要大约 4 个小时才能执行。两者都使用 SQLAlchemy:
def first():
session = DBSession
rows = session.query(Mytable).order_by(Mytable.col1.desc())[:150]
for i,row in enumerate(rows):
time.sleep(100)
print i, row.accession
def second():
print "going onto second function"
session = DBSession
new_row = session.query(Anothertable).order_by(Anothertable.col1.desc()).first()
print 'New Row: ', new_row.accession
first()
second()
这是我定义 DBSession 的方式:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import create_engine
engine = create_engine('mysql://blah:blah@blah/blahblah',echo=False,pool_recycle=3600*12)
DBSession = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.metadata.bind = engine
first() 完成得很好(大约需要 4 小时),我看到打印了“进入第二个函数”,然后它立即给我一个错误:
sqlalchemy.exc.OperationalError: (OperationalError) (2006, 'MySQL server has gone away')
通过阅读文档,我认为分配 session=DBSession 会得到两个不同的会话实例,因此 second() 不会超时。我也试过玩 pool_recycle ,这似乎没有任何效果。在现实世界中,我无法将 first() 和 second() 拆分为 2 个脚本:second() 必须在 first() 之后立即执行
【问题讨论】:
-
我不知道您为什么会收到此错误,但我想指出,使用
scoped_session您将收到完全相同的 Session 实例。请在Contextual/Thread-local Sessions文档页面上阅读更多信息。但是,如果您不能拆分first()和second(),我认为它们必须在同一个事务中运行(必须是atomic)。
标签: python mysql sqlalchemy