Django provides session support out-of-the-box and stores sessions in the django_session
database table. Django leaves it up to the project maintainers to purge sessions in their Django project. This means that if it's not done on a regular basis the table grows infinitely. However, they provide a simple command called clearsessions
for it. Using it within a Celery task in a cron schedule resolves any long-term storage issues with large tables for sessions. The below solution requires both Celery for the task and Celery-beat for the cron schedule.
config/celery_app.py
app.conf.beat_schedule = {
# Clear expired sessions
"clear_sessions": {
"task": "config.celery_app.clear_sessions",
"schedule": crontab(hour=0, minute=0, day_of_week=0),
},
... other tasks
}
@app.task
def clear_sessions():
"""Clear expired sessions by using Django management command."""
management.call_command("clearsessions")
Recently, the django_session
table grew to a couple of gigabytes and I added this solution to clear the table. Now it's a default addition to any Django and Celery project.