pythonsqlalchemyflask-sqlalchemy

Should session be closed after each query in sqlalchemy?


I am using sqlalchemy orm query, I want to know if closing session after each query is really necessary?

def foo():
   session = get_orm_sqlalchemy_session()
   try:
      pass
   except Exception as ex:
      logging.error(str(ex), stack_info=traceback.print_exc())
   finally:
      session.close()

Solution

  • Closing the session after each query is a common practice to ensure that database connections are properly managed and resources are released.

    There are several reasons why a session should be closed:

    Note that: scoped_session of SQLAlchemy provides thread-local sessions, the framework can handle session lifecycle automatically.