Skip to content


Fixed #17083 -- Allow cached based sessions to use a custom cache backend #169

wants to merge 1 commit into from

3 participants


Django currently lacks a way of using a custom cache backend in django.contrib.sessions - it always uses the default backend.

This commit will default to the "sessions" backend, but will fall back to the "default" backend, this is similar to django.contrib.staticfiles behaviour.

Django member

Can you please add tests which check that the backend in question is actually used?

@aaugustin aaugustin closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Showing with 17 additions and 1 deletion.
  1. +6 −1 django/contrib/sessions/backends/
  2. +4 −0 docs/releases/1.5.txt
  3. +7 −0 docs/topics/http/sessions.txt
7 django/contrib/sessions/backends/
@@ -1,5 +1,5 @@
from django.contrib.sessions.backends.base import SessionBase, CreateError
-from django.core.cache import cache
+from django.core.cache import get_cache, InvalidCacheBackendError, cache
KEY_PREFIX = "django.contrib.sessions.cache"
@@ -10,6 +10,11 @@ class SessionStore(SessionBase):
def __init__(self, session_key=None):
self._cache = cache
+ try:
+ self._cache = get_cache('sessions')
+ except InvalidCacheBackendError:
+ # Use the default backend
+ self._cache = cache
super(SessionStore, self).__init__(session_key)
4 docs/releases/1.5.txt
@@ -102,6 +102,10 @@ Django 1.5 also includes several smaller improvements worth noting:
* In the localflavor for Canada, "pq" was added to the acceptable codes for
Quebec. It's an old abbreviation.
+* :ref:`Cached-based sessions <cached-sessions-backend>` can now use a custom
+ cache backend. Add a ``'sessions'`` entry to the :setting:`CACHES` setting to
+ use a different backend instead of the ``'default'`` backend.
Backwards incompatible changes in 1.5
7 docs/topics/http/sessions.txt
@@ -45,6 +45,8 @@ If you want to use a database-backed session, you need to add
Once you have configured your installation, run `` syncdb``
to install the single database table that stores session data.
+.. _cached-sessions-backend:
Using cached sessions
@@ -77,6 +79,11 @@ the cache:
the database. Session reads only use the database if the data is not
already in the cache.
+.. versionchanged:: 1.5
+ Cached sessions use the ``'sessions'`` entry in the :setting:`CACHES`
+ setting, but will fall back to the ``'default'`` cache backend if this
+ doesn't exist.
Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the ``cached_db`` backend will be fast
enough, but if you need that last bit of performance, and are willing to let
Something went wrong with that request. Please try again.