CNHAustin
CNHAustin

Reputation: 3

Flask-Session (filesystem): session files are not deleted after PERMANENT_SESSION_LIFETIME

I am trying to test server-side Flask sessions using Flask-Session. I am attempting to have sessions last only a minute in order to test that the session's files get deleted, but even when I set the session time to one (1) minute, the session's files are not cleared. I am trying to implement something similar the solution provided here, but it doesn't seem to be working...

Here's my simple application:

# IMPORTS
from flask import Flask, request, render_template, session
from flask_session import Session
from datetime import datetime, timedelta


# APP SETUP
app = Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=1)
app.secret_key = "czOWE9w7nfe7Z6UpLPaEHC2NXMJzUI57"
Session(app)

As I expect, the files are being generated under /flask_session: image of folder with files in it

However, due to app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=1) I am expecting at least one of the following to occur:

  1. after one minute the files will be deleted while still using the application.

  2. one minute after closing the window the files will be deleted.

Neither of these outcomes occur :( What gives?

Upvotes: 0

Views: 1082

Answers (1)

Dauros
Dauros

Reputation: 10502

Flask-Session uses Cachelib's File backend. If you look at its source code:

def set(
    self,
    key: str,
    value: _t.Any,
    timeout: _t.Optional[int] = None,
    mgmt_element: bool = False,
) -> bool:
    # Management elements have no timeout
    if mgmt_element:
        timeout = 0
    # Don't prune on management element update, to avoid loop
    else:
        self._prune()
    ...

you see that it calls the _prune() method at the beginning of key-set method. So the expired elements will be cleared at the next time you set a new element and the conditions for clearing are satisfied. It's because you don't have a background worker/cron that clears automatically the expired elements. Furthermore there is the file count threshold setting: SESSION_FILE_THRESHOLD that is by default 500. You need to decrease that as well if you want to increase the frequency of clearing.

Upvotes: 0

Related Questions