diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py
index 20d1279..d5e2fe3 100644
a
|
b
|
class SessionBase(object):
|
281 | 281 | Loads the session data and returns a dictionary. |
282 | 282 | """ |
283 | 283 | raise NotImplementedError |
| 284 | |
| 285 | @classmethod |
| 286 | def cleanup(cls): |
| 287 | """ |
| 288 | Cleaunp the expired sessions |
| 289 | """ |
| 290 | raise NotImplementedError |
diff --git a/django/contrib/sessions/backends/db.py b/django/contrib/sessions/backends/db.py
index 3dd0d95..e443958 100644
a
|
b
|
class SessionStore(SessionBase):
|
72 | 72 | except Session.DoesNotExist: |
73 | 73 | pass |
74 | 74 | |
| 75 | @classmethod |
| 76 | def cleanup(cls): |
| 77 | Session.objects.filter(expire_date__lt=timezone.now()).delete() |
| 78 | transaction.commit_unless_managed() |
75 | 79 | |
76 | 80 | # At bottom to avoid circular import |
77 | 81 | from django.contrib.sessions.models import Session |
diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py
index 0f86908..c00e3f1 100644
a
|
b
|
class SessionStore(SessionBase):
|
142 | 142 | |
143 | 143 | def clean(self): |
144 | 144 | pass |
| 145 | |
| 146 | @classmethod |
| 147 | def cleanup(cls): |
| 148 | storage_path = getattr(settings, "SESSION_FILE_PATH", tempfile.gettempdir()) |
| 149 | file_prefix = settings.SESSION_COOKIE_NAME |
| 150 | |
| 151 | # Get all file sessions stored |
| 152 | sessions = [cls(session[len(file_prefix):]) |
| 153 | for session in os.listdir(storage_path) |
| 154 | if session.startswith(file_prefix)] |
| 155 | |
| 156 | for session in sessions: |
| 157 | old_key = session.session_key |
| 158 | session.load() |
| 159 | new_key = session.session_key |
| 160 | |
| 161 | # The key was changed i.e. new session created, so the existing one |
| 162 | # was invalid. Lests clean it all up |
| 163 | if old_key != new_key: |
| 164 | session.delete(old_key) |
| 165 | session.delete(new_key) |
diff --git a/django/core/management/commands/cleanup.py b/django/core/management/commands/cleanup.py
index e19d164..5a91cc1 100644
a
|
b
|
|
1 | 1 | from django.core.management.base import NoArgsCommand |
2 | | from django.utils import timezone |
| 2 | from django.utils.importlib import import_module |
| 3 | from django.conf import settings |
3 | 4 | |
4 | 5 | class Command(NoArgsCommand): |
5 | 6 | help = "Can be run as a cronjob or directly to clean out old data from the database (only expired sessions at the moment)." |
6 | 7 | |
7 | 8 | def handle_noargs(self, **options): |
8 | | from django.db import transaction |
9 | | from django.contrib.sessions.models import Session |
10 | | Session.objects.filter(expire_date__lt=timezone.now()).delete() |
11 | | transaction.commit_unless_managed() |
| 9 | engine = import_module(settings.SESSION_ENGINE) |
| 10 | engine.SessionStore.cleanup() |