Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 917
Jahongir Rahmonov Avatar asked May 20 '15 06:05

Jahongir Rahmonov


People also ask

How does Django save session data?

By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache. When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute.

Where session is stored?

Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as the server. Read through this article to find out more about cookies and sessions and how they are different from each other.

How does Django store objects in session?

Objects cannot be stored in session from Django 1.6 or above. If you don't want to change the behavior of the cookie value(of a object), you can add a dictionary there. This can be used for non database objects like class object etc. Hope it will help you!


1 Answers

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.

like image 65
bruno desthuilliers Avatar answered Oct 05 '22 01:10

bruno desthuilliers