> user = Session.query(User).filter_by(id=user_id).first()
> print("Active Session", {'id': user.id, 'email': user.email} )
> Session.commit()
> Session.close()
> user = Session.query(User).filter_by(id=user_id).first()
> print("After closing session", {'id': user.id, 'email': user.email})
i am trying to close session using python and sqlalchemy but after
closing session still getting session and user infor
2
Answers
This is a normal behavior in sqlalchemy, because the user information that were loaded when the session was still active, can still be retrieved when the session is closed, because it is still available in memory. But you cannot retrieve unloaded user information when the session is closed.
You can learn more by visiting the documentation Opening and closing a session
Actually it is the default behaviour in SQLAlchemy. Session.close() does not close the session, instead it releases resources that are being used and places it in connection pool for reuse.
You can use engine.dispose() to close all the sessions in connection pool.