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