Skip to content
Advertisement

Flask-sqlalchemy: When to close sessions?

I have created a python webapp with Flask and it seems like I am having connection issues with the database. I think this is because I don’t close my sessions somewhere in my code.

I have

db = SQLAlchemy(app)

for the database and use

@views.route('/test/', methods=['GET', 'POST'])
def test():
    db.session.add(something)
    db.session.commit()

@views.route('/another_page/', methods=['GET', 'POST'])
def page():
    some_records = User.query.get(some_ids)

for adding records to the database.

When do I have to close my session in this case? Is there a way to close the connection after the user leaves? Should I close every time a page is done with the database? Do I need to close my connection after a query?

Advertisement

Answer

The documentation says next:

As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module:

from yourapplication.database import db_session

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

UPD: In case of Flask-SQLAlchemy this staff is hardcoded, thus you don’t need to care about it when develop.

Advertisement