Skip to main content

Expiry rules for Django sessions.

Project description



Expiry rules for Django sessions.


Install using pip

pip install django-expiry

or Pipenv

pipenv install django-expiry

Add expiry to your INSTALLED_APPS setting


Add expiry.middleware.ExpirySessionMiddleware to your middleware setting


or to middleware classes if your Django is <= 1.9


The middleware will process rules and default ages for fresh sessions.



Default ages can be set for anonymous and authenticated users. When not set, the session age behaviour will default to Django.

Default: not set.

The default age of an anonymous session, in seconds.

Default: False

Keeps the authenticated session alive, refreshing its expiry for every request, according to its default value and rules.

Default: not set.

The default age of an authenticated session, in seconds.

Default: False

Keeps the anonymous session alive, refreshing its expiry for every request, according to its default value and rules.


A set of rules should be defined in your settings file. You can have rules for anonymous users and authenticated users, handled separately.

Expiry rules for authenticated users only

Processed whenever an user logs in. Its callable should always accept an user and a request object.

    (lambda request, user: user.is_staff, 300),
    (lambda request, user: user.is_superuser, datetime.timedelta(weeks=2)),
    (lambda request, user: user.has_perms('hero'), 99999999),

Expiry rules for anonymous users only

Processed whenever a session is fresh. Rules are triggered in ExpirySessionMiddleware.

    (lambda request: request.META.get('REMOTE_ADDR') == '', 999)

Rule composition

A rule is a tuple composed by:

  • A callable or the path to a callable that will validate it
  • An expiry (seconds, datetime, timedelta)

Note that, for datetime and timedelta expiries, serialization won't work unless you are using the PickleSerializer.
Read more about it here.

In the examples above, all rules are lambdas, but you can also send the path to a function that will validate it.

    ('app.module.complex_rule', datetime.timedelta(days=64)),

Then define the rule in that specific module:

def complex_rule(user, request):

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-expiry-0.2.3.tar.gz (3.9 kB view hashes)

Uploaded source

Built Distribution

django_expiry-0.2.3-py3-none-any.whl (5.8 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page