pythondjangosessioncookiesdjango-sessions

Where does Django store sessions?


I have this code in my project that assigns a unique id to an anomymous user and saves it in a session:

user_id = str(uuid.uuid4())[:5]
request.session['nonuserid'] = user_id

Documentation says that sessions are stored in my database. I thought it would save it in django_session table. However, everytime a unique is created and saved in session(above code), no row is added to that table.

Then I checked cookies in Resources. There is no key with name nonusedid. Just some sessionid

So, where does it store the session data I created?

Relevant part of Settings.py

MIDDLEWARE_CLASSES = (
    # Default Django middleware.
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

DJANGO_APPS = (
    # Default Django apps:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

Solution

  • I thought it would save it in django_session table. However, everytime a unique is created and saved in session(above code), no row is added to that table.

    Hopefully a new row is not added each time you add a key/value to the current session. Session's data are stored in serialized form (in the django_session.session_data field), and a new row is added only when a new session is started - all subsequent writes to the session will only update the session_data field's content.