maro
maro

Reputation: 77

Remove session on each request when using raw sqlalchemy

I must use raw SqlAlchemy library with Flask app because of some things.

When I read this link, I ran into this: "To use SQLAlchemy in a declarative way with your application, you just have to put the following code into your application module. Flask will automatically remove database sessions at the end of the request or when the application shuts down". Here is the code:

from yourapplication.database import db_session

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

Why do I need to do this? What would happen if I don't add this code?

Upvotes: 0

Views: 451

Answers (1)

Attack68
Attack68

Reputation: 4765

Without providing a definitive reason for why you need it let me suggest a practical reason.

sessions exists to coordinate changes to the database before actually committing them and permanently saving them. When you execute session.commit() the complete set of changes is attempted. It will either fail in full, or succeed in full. If you do not clear the session after every request then it will persist and some of the following might occur:

1) You perform a bad request which modifies the session with break causing elements, and leave the session open. You perform a new request (in the same session) which is valid and attempt to commit. It fails because of the error in the first request. You application is not decoupled and separated sensibly into small modular components. It is difficult to debug as you expect the fault in the second request.

2) You perform a valid request and make some changes. Perhaps a flush is performed to access id's prior to commit. The session is not committed, however. At some unspecified time in the future another request is made on the existing (open) session. It has now gone stale since many more changes have taken place in the meantime. A new commit might fail and again be difficult to debug.

.. probably many more reasons.

Upvotes: 1

Related Questions