According to the sqlalchemy document, the lifecycle of the sqlalchemy session in the web application context should be:
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 <-
See: http://www.sqlalchemy.org/docs/05/session.html#lifespan-of-a-contextual-session
However, in the example of using sqlalchemy In the cookbook of web. py, the session resource of sqlalchemy is not released at the end, which should be as follows:
Def load_sqla (handler ):
Web. ctx. orm = scoped_session (sessionmaker (bind = engine ))
Try:
Return handler ()
Failed T web. HTTPError:
Web. ctx. orm. commit ()
Raise
Except t:
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 () # <=-close the session, or use. remove ()