随笔-153  评论-1709  文章-1 

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()

  

posted on 2011-08-10 21:24 Q.Lee.lulu 阅读(...) 评论(...) 编辑 收藏