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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With