






















按照sqlalchemy的文档中关于sqlalchemy的session在web应用上下文的生命周期应该是:
Web Server Web Framework User-defined Controller Call
-------------- -------------- ------------------------------
web request ->
call controller -> # call Session(). this establishes a new,
# contextual Session.
session = Session()# load some objects, save some changes
= session.query(MyClass).all()
objects# some other code calls Session, it
's the
# same contextual session as "sess"
session2 = Session()
session2.add(foo)
session2.commit()# generate content to be returned
return generate_content()
Session.remove() <-
web response <-
见:http://www.sqlalchemy.org/docs/05/session.html#lifespan-of-a-contextual-session
不过web.py的cookbook中关于使用sqlalchemy的示例中,最后并没有释放sqlalchemy的session资源,正确的应该如下:
def load_sqla(handler):
web.ctx.orm = scoped_session(sessionmaker(bind=engine))
try:
return handler()
except web.HTTPError:
web.ctx.orm.commit()
raise
except:
web.ctx.orm.rollback()
raise
finally:
web.ctx.orm.commit()
# If the above alone doesn't work, uncomment
# the following line:
#web.ctx.orm.expunge_all()
web.ctx.orm.close() # <=- 关闭session,或者用 .remove()
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。