How do I close a Flask-SQLAlchemy connection that I used in a Thread?

Solution 1
def cleanup(session):
    """
    This method cleans up the session object and closes the connection pool using the dispose 
    method.
    """
    session.close()
    engine_container.dispose()
finally:
    cleanup(db.session)
from threading import Thread
from sqlalchemy.pool import NullPool
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

db = SQLAlchemy()
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///testdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'poolclass': NullPool,
}
db.app = app
db.init_app(app)
engine_container = db.get_engine(app)


class TestModel(db.Model):
    __tablename__ = "test_table"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)


@app.route('/test-connection')
def test_connection():
    def run_test():
        try:
            models = TestModel.query.all()
            print(models)
        except Exception as err:
            raise err
        finally:
            cleanup(db.session)

    thread = Thread(target=run_test)
    thread.start()
    return "OK"


def cleanup(session):
    """
    This method cleans up the session object and also closes the connection pool using the dispose method.
    """
    session.close()
    engine_container.dispose()


app.run(debug=True, host='0.0.0.0')
Solution 2
SQLALCHEMY_ENGINE_OPTIONS = {
    pool_size=20,
    pool_reset_on_return='commit', # looks like postgres likes this more than rollback
    pool_timeout=5, # try a low value here maybe
}