Search code examples
pythonflaskflask-session

List Active Sessions in Flask


I have a Flask Server, and I'm using the session object in requests. However, I also have a background thread that runs occasionally for cleanup, which does not run within any handler.

How would I generate a list of active session objects across all clients? So for example, if Client A has Session A, Client B has Session B, Client C has Session C, I would like to access a list along the lines of [Session A, Session B, Session C].

It appears there's no mention of this in the Flask or Flask-Session documentation, but it seems like this should be possible since we're obviously storing all session information somewhere.


Solution

  • For this particular task you would need to configure a server-side storage for sessions because Flask uses cookies for session management Flask Sessions.

    Suppose you decide to use a Redis backend to store sessions you will have to install the redis server Redis Installation, the python redis library and Flask-Session librarypip install Flask-Session redis

    If you are using Flask Factory, setup the storage config like

    app.config.from_mapping(
    SECRET_KEY = <your secret key>
    ...
    SESSION_TYPE = 'redis',
    SESSION_PERMANENT = False,
    SESSION_USE_SIGNER = True,
    SESSION_KEY_PREFIX = 'session:',
    SESSION_REDIS = redis.StrictRedis(host='localhost', port=6379, db=0),
    ...
    )
    

    Then initialize the application inside the Session manager as

    Session(app)
    

    later in your route you can access the sessions by adding

    redis_conn = current_app.config['SESSION_REDIS']
    session_keys = redis_conn.keys(f"{current_app.config['SESSION_KEY_PREFIX']}*")
    
    for key in session_keys:
        session_data = redis_conn.get(key)
    // do whatever you want to do with the session_data  e.g. close any session associated with the username that requested to close other sessions