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

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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。