I could properly experiment when session is and isn't saved in Django as shown in my answer referring When sessions are saved. *I use Django 4.2.3.
But if I run all cases together as shown below (The 1st run):
# "views.py"
from django.http import HttpResponse
def test(request):
# The 1st case
request.session["foo"] = "bar"
# The 2nd case
del request.session["foo"]
# The 3rd case
request.session["foo"] = {}
# The 4th case
request.session["foo"]["bar"] = "baz"
return HttpResponse('Test')
Then, the 4th case is unexpectedly saved as shown below (The 2nd run):
# "views.py"
from django.http import HttpResponse
def test(request):
print(request.session.get('foo')) # {'bar': 'baz'}
return HttpResponse('Test')
Because if I run the 1st, 2nd and 3rd cases together except the 4th case as shown below (The 1st run):
# "views.py"
from django.http import HttpResponse
def test(request):
# The 1st case
request.session["foo"] = "bar"
# The 2nd case
del request.session["foo"]
# The 3rd case
request.session["foo"] = {}
return HttpResponse('Test')
Then, run only the 4th case as shown below (The 2nd run):
# "views.py"
from django.http import HttpResponse
def test(request):
# The 4th case
request.session["foo"]["bar"] = "baz"
return HttpResponse('Test')
Then, the 4th case is not saved as shown below (The 3rd run):
# "views.py"
from django.http import HttpResponse
def test(request):
print(request.session.get('foo')) # {}
return HttpResponse('Test')
Actually, I don't use the code below in the code above as you can see:
request.session.modified = True
And, I set SESSION_SAVE_EVERY_REQUEST False
in settings.py
as shown below:
# "settings.py"
SESSION_SAVE_EVERY_REQUEST = False
So, why is the 4th case unexpectedly saved if I run all cases together?
django_session
table in database. – PentobarbitalSESSION_SAVE_EVERY_REQUEST
set toFalse
etc. – Rutheniousrequest.session["foo"] = {}
(3rd case) the session is altered and will be saved. Then you dorequest.session["foo"]["bar"] = "baz"
(4th case) and since you do it before the session is saved this data will be part of the session too. – Genicrequest.session.modified = True
, so if you don't setrequest.session['foo'] = {}
in the same request, then it will not save. – Rutheniousrequest.session.modified
during the response. In other words: the session is saved when the response is done, not every time whenrequest.session
is altered. You can find the code in django/contrib/sessions/middleware.py. – Genic