Skip to content
loading...

re: Flask and SQLAlchemy without the Flask-SQLAlchemy Extension VIEW POST

FULL DISCUSSION
 

Hi @nestedsoftware .

Why do we need to remove session on teardown. What would happen if we don't release the resources used by a session after each request?

 

That's a good question @marinkreso95 ! It's important to make sure to release any database/transactional resources that are no longer needed by the current thread. For example, if a connection to the db used by Session is not released back to its connection pool, it won't be available for use by another thread. Any external resources like this should be cleaned up.

The documentation says that these resources will be released when the current thread ends:

The scoped_session.remove() method, as always, removes the current Session associated with the thread, if any. However, one advantage of the threading.local() object is that if the application thread itself ends, the “storage” for that thread is also garbage collected. So it is in fact “safe” to use thread local scope with an application that spawns and tears down threads, without the need to call scoped_session.remove(). However, the scope of transactions themselves, i.e. ending them via Session.commit() or Session.rollback(), will usually still be something that must be explicitly arranged for at the appropriate time, unless the application actually ties the lifespan of a thread to the lifespan of a transaction.

So, depending on how Flask handles threads, we may not need to do this ourselves. I think it's still better to call Session.remove explicitly when the request is done, just to be certain.

 

Thank you very much for quick response, and great article @nestedsoftware

code of conduct - report abuse