Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manage cleaning up expired sessions using Flask-KVSession?

Tags:

session

flask

From the documentation http://flask-kvsession.readthedocs.org/en/0.3.1/ atcleanup_sessions(), it says this method should be called periodically to clean up expired sessions.

Does it mean that the session memory usage will expand during the lifetime of the application if I do not clean it up?

What are the bad implications if I do not clean them up periodically?

What would be some good ways to schedule the periodic cleanup within the application?

Can I use Redis as the storage backend and set an expiry automatically?

like image 282
hllau Avatar asked Oct 05 '22 09:10

hllau


2 Answers

If you use RedisStore, KVSession would pick the flask config item PERMANENT_SESSION_LIFETIME and do session cleanup automatically. Only for the Backends that don't support it TimeToLiveMixin interface you have to do it by manually.

Expiring sessions Sessions will expire, causing them to be invalid. To be automatically removed from the backend as well, that backend must support the TimeToLiveMixin interface; example backends that support this are are RedisStore and MemcacheStore.

When using a different backend without time-to-live support, for example flat files through FilesystemStore, cleanup_sessions() can be called periodically to remove unused sessions.

like image 112
Saravanan Kalirajan Avatar answered Oct 13 '22 10:10

Saravanan Kalirajan


You can register a 'after_request' or 'before_request' to handle cleanup periodically.

from flask import Flask

from flask.ext.kvsession import KVSessionExtension
from simplekv.db.sql import SQLAlchemyStore
from sqlalchemy import create_engine, MetaData

# init app
app = Flask(__name__)

# init Flask-KVSession
engine = create_engine('mysql+pymysql://user:password@localhost/kvsession_db')
metadata = MetaData(bind=engine)
store = SQLAlchemyStore(engine, metadata, 'kvsession_table')
metadata.create_all()
kvsession_extension = KVSessionExtension(store, app)

# perdiocally cleanup expired sessions
import time
# do cleanup per day. You may store this value in app.config
SESSION_CLEANUP_INTERVAL = 60 * 60 * 24
deadline = None
@app.after_request
def cleanup_expired_sessions():
    global SESSION_CLEANUP_INTERVAL, deadline
    if deadline is None:
        kvsession_extension.cleanup_sessions(app)
        deadline = time.time() = SESSION_CLEANUP_INTERVAL
    else:
        if time.time() >= deadline:
            # time to do cleanup
            kvsession_extension.cleanup(app)
            # update deadline
            deadline = time.time() + SESSION_CLEANUP_INTERVAL
like image 44
semon Avatar answered Oct 13 '22 11:10

semon