Clean up DJANGO_SESSION table automatically.

Unfortunately Django doesn’t clean up the sessions table so you could end up having hundreds of thousands of entries slowing down the backup and restore procedure tremendously. To fix this issue please follow this guide.

First all we need to create an SQL script that will move data around to keep the current sessions only. I am using the code published on djangosnippets.org.

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` > now();

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

DROP TABLE `django_session_old_master`;

Now we need to automate the cleanup process. We need to run this script from every day at a given time. The command to run this script from the command line is:

mysql -u [username] -p[password-no-space-between-p-and-password]  [database_name] < cleanup.sql

We added this command to the cleanup.sh shell script which is then scheduled to run at 2.00am every day.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.