Permalink
Browse files

Added cleanup classmethod to SessionBase

  • Loading branch information...
1 parent ad82b6e commit 969822aa8b51af7840d5809b649101b291d26623 @tricoder42 tricoder42 committed Oct 26, 2012
@@ -281,3 +281,10 @@ def load(self):
Loads the session data and returns a dictionary.
"""
raise NotImplementedError
+
+ @classmethod
+ def cleanup(cls):
+ """
+ Cleanup the expired sessions.
+ """
+ raise NotImplementedError
@@ -71,6 +71,10 @@ def delete(self, session_key=None):
except Session.DoesNotExist:
pass
+ @classmethod
+ def cleanup(cls):
+ Session.objects.filter(expire_date__lt=timezone.now()).delete()
+ transaction.commit_unless_managed()
# At bottom to avoid circular import
from django.contrib.sessions.models import Session
@@ -142,3 +142,24 @@ def delete(self, session_key=None):
def clean(self):
pass
+
+ @classmethod
+ def cleanup(cls):
+ storage_path = getattr(settings, "SESSION_FILE_PATH", tempfile.gettempdir())
+ file_prefix = settings.SESSION_COOKIE_NAME
+
+ # Get all file sessions stored
+ sessions = [cls(session[len(file_prefix):])
+ for session in os.listdir(storage_path)
+ if session.startswith(file_prefix)]
+
+ for session in sessions:
+ old_key = session.session_key
+ session.load()
+ new_key = session.session_key
+
+ # The key was changed i.e. new session created, so the existing one
+ # was invalid. Lests clean it all up
+ if old_key != new_key:
+ session.delete(old_key)
+ session.delete(new_key)
@@ -1,12 +1,11 @@
from django.core.management.base import NoArgsCommand
-from django.utils import timezone
+from django.utils.importlib import import_module
+from django.conf import settings
class Command(NoArgsCommand):
help = "Clean expired sessions."
def handle_noargs(self, **options):
- from django.db import transaction
- from django.contrib.sessions.models import Session
- Session.objects.filter(expire_date__lt=timezone.now()).delete()
- transaction.commit_unless_managed()
+ engine = import_module(settings.SESSION_ENGINE)
+ engine.SessionStore.cleanup()
@@ -261,6 +261,11 @@ You can edit it multiple times.
Returns either ``True`` or ``False``, depending on whether the user's
session cookie will expire when the user's Web browser is closed.
+ .. method:: SessionBase.cleanup()
+
+ Class method which cleans up expired session (eg. delete related rows
+ in database, files, etc.)
+
Session object guidelines
-------------------------

0 comments on commit 969822a

Please sign in to comment.