sqlalchemy在web.py中的session使用
按照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
objects = session.query(MyClass).all()
# 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()
作者:QLeelulu
出处:http://QLeelulu.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利
出处:http://QLeelulu.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利