Sqlalchemy's session usage in web. py

Source: Internet
Author: User

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

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.