delphij's Chaos

原在新浪,FreeBSD Committer,现在国外,国内 FreeBSD 社区主要发起人,Python 重度用户 ...

↑我也要推荐

sqlalchemy 在 web.py 中的 session 使用,作者 @QLeelulu

发布时间:2011-08-13 16:29:14, 关注:+8377, 赞美:+12, 不爽:+8

本文标签: sqlalchemy session

原始出处: lulu Studio

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

如果你觉得本站对你有帮助,欢迎向本站赞助 :P

使用支付宝捐赠

Copyright© Python4cn(news, jobs) simple-is-better.com, 技术驱动:powered by web.py 空间主机:Webfaction

版权申明:文章转载已注明出处,如有疑问请来信咨询。本站为 python 语言推广公益网站,与 python 官方没有任何关系。

联系/投搞/留言: en.simple.is.better@gmail.com 向本站捐赠