0

I need to be able to log when Flask-KVSession sessions time out. Is there a easy way to catch session timeouts and log when they occur?

davidism
  • 121,510
  • 29
  • 395
  • 339
calk93
  • 109
  • 1
  • 1
  • 4

1 Answers1

1

You can't know in real time. The session id is stored in a cookie, which is only sent by the browser when making requests. It won't send a cookie that has expired. KVSession won't load a session if it doesn't receive a valid cookie. There's no way to distinguish between a new session and an expired session because neither would send a cookie.

The extension does have a cleanup_sessions method, which will look through all the keys in the store and check if they're expired, but that must be called manually periodically, it's not an automatic process.

You can write a similar method to log before removing the expired sessions, but again you need to run this on your own schedule. The following is a copy of the cleanup_sessions method with logging added.

from flask import current_app
from flask_kvsession import KVSessionExtension as _BaseKVSessionExtension, SessionID

class KVSessionExtension(_BaseKVSessionExtension):
    def log_cleanup_sessions(self, app=None):
        if not app:
            app = current_app

        now = datetime.utcnow()

        for key in app.kvsession_store.keys():
            m = self.key_regex.match(key)

            if not m:
                continue

            sid = SessionID.unserialize(key)

            if sid.has_expired(app.permanent_session_lifetime, now):
                app.logger.info('Removing session %s', key)
                app.kvsession_store.delete(key)
davidism
  • 121,510
  • 29
  • 395
  • 339