Simple Django User Session Clearing using Celery

1 year ago 1040 views
1 min read

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.


Similar Posts

Django Development and Production Logging

12 min read

Django comes with many great built-in features, logging is one of them. Pre-configured logging setups that vary between development (debug mode) and production environments. Easy integration to send you emails on errors, out-of-the-box support for various settings as log levels …


Django Error Tracking and Performance Monitoring with Sentry

6 min read

As good as a framework that Django is, the default method of sending an email when getting an error leave much to be desired. The database or cache acting flaky? Expect 1000s of emails depicting that error, which usually does …


Celery Monitoring with Prometheus and Grafana

5 min read

Celery is a python project used for asynchronous job processing and task scheduling in web applications or distributed systems. It is very commonly used together with Django, Celery as the asynchronous job processor and Django as the web framework. Celery …