Life cycle Management of SQLAlchemy session in Web projects

Source: Internet
Author: User

Suppose you already have a Session factory class:

Session = sessionmaker(bind=some_engine)

Then the life cycle of the session instance can be:

Shortest mode-Create a new session per request, close when you're done
@contextmanagerdef get_session_scope():    try:        s = Session()        yield s        s.commit()    except:        s.rollback()    finally:        s.close()

This model is not suitable for Web projects or the disadvantage is that it consumes too fast the connection pool (db pool). In practice, the connection to the closed session did not return to the available state immediately. Therefore, when the request is frequent, there is a case for waiting for a connection.

Longest mode-full use of a session
session = Session()

This approach is more inappropriate for Web projects. Because of the document description according to SQLAlchemy:

The Session object is entirely designed to be used in a non-concurrent fashion, which in terms of multithreading means “only in one thread at a time”.

The session is not thread-safe. This concurrent use of the session will cause an error.

Thread-local mode-Lifecycle and request synchronization
@app.before_requestdef init_session():    request.session = Session()@app.tear_down_requestdef close_session():    request.session.close()

This is actually the most suitable for Web project session management mode. (pseudo-code does not write commit and rollback, you can add it yourself) This avoids the excessive consumption of connection pool, and avoids the concurrency problem. This is also the recommended practice in the SQLAlchemy documentation.

Life cycle Management of SQLAlchemy session in Web projects

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.