Return to Snippet

Revision: 54514
at December 30, 2011 23:12 by magicrebirth


Initial Code
DROP TABLE IF EXISTS `django_session_cleaned`;
CREATE TABLE `django_session_cleaned` (
  `session_key` varchar(40) NOT NULL,
  `session_data` longtext NOT NULL,
  `expire_date` datetime NOT NULL,
  PRIMARY KEY  (`session_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `django_session_cleaned` SELECT * FROM `django_session` WHERE `expire_date` > CURRENT_TIMESTAMP;

RENAME TABLE `django_session` TO `django_session_old_master`, `django_session_cleaned` TO `django_session`;

DROP TABLE `django_session_old_master`;

Initial URL
http://djangosnippets.org/snippets/1273/

Initial Description
While django provides the django_admin.py cleanup script, if sessions get out of control sometimes you have to go lower level to get everything cleaned up. If the problem gets out of hand and you hit the resource limits of the machine, it is very difficult to get anything done in the database.

Attached is SQL code which was used to cleanup 27GB of expired session data in 3h. Run it like this to make sure it runs to completion:

`nohup mysql --user=username --password=password --host=hostname database < delete_expired_sessions.sql`

nohup causes the script to run detached from a terminal, so if your session gets disconnected it will keep running.

p.s.
An alternative approach is to launch this command from the shell:

DELETE FROM django_session WHERE expire_date < NOW();

or 

DELETE FROM django_session WHERE expire_date < "2011-12-10 00:00:00";

Initial Title
Clean up expired django.contrib.session\'s in a huge MySQL InnoDB table

Initial Tags
sql, django

Initial Language
Django