4

I implemented a server side Session in Flask with SQLAlchemy based on this snippit:

class SqlAlchemySession(CallbackDict, SessionMixing):
    ...

class SqlAlchemySessionInterface(SessionInterface):
    def __init__(self, db):
        self.db = db

    def open_session(self, app, request):
        ...

    def save_session(self, app, session, response):
        ...

Everything works as expected. When the user logs in, a session is stored in the database, and the session id is placed in a cookie and returned to the user. When the user logs out, session.clear() is called, and the cookie is removed from the user.

However, the session is not deleted from the database. I was hoping that I could implement this logic in my SqlAlchemySessionInterface class, as opposed to defining a function and calling this instead of session.clear().

Likewise, in the sessions.py code, there isn't any reference to clear, and the only time a cookie is deleted is if the session was modified.

The API documentation for sessions also doesn't indicate how the clear method works.

Would anyone know of a way of accomplishing this, other than replacing all my calls to session.clear() with:

def clear_session():
    sid = session.get('sid')
    if sid:
        db.session.query(DBSession).filter_by(sid=sid).delete()
        db.session.commit()
    session.clear()
Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • Possible duplicate of http://stackoverflow.com/questions/13735024/invalidate-an-old-session-in-flask – Zixian Cai Oct 08 '16 at 09:24
  • @IvanCai This question is about deleting the database record that identifies a session, not about clearing the cookie. – Matthew Moisen Oct 08 '16 at 17:53
  • @MatthewMoisen Did you ever found a solution? In my database, also sessions pile up. – Sebi Dec 16 '20 at 09:47
  • I use server-side sessions in conjunction with Flask-Login. In Flask-Login you are supposed to call `flask_login.logout_user()`, when someone hits the endpoint to logout. I found that I also need to call `session.clear()` to get this session also removed from the DB. Main problem is that now I get a lot of sessions in my DB for anonymous users. Those sessions never get cleared as there is no job to remove expired sessions :-( – Sebi Dec 16 '20 at 10:08

1 Answers1

-1

If you want to remove duplication, you can define a function called logout_user

In that function, you can remove the session record from your database as well as session.clear().

Call this function when \logout or wherever suitable.

Zixian Cai
  • 945
  • 1
  • 10
  • 17