Reputation: 2659
I've got vanilla django project with app called 'app' . It has views.py and middleweres.py.
#views.py
from django.http.response import HttpResponse
def home(request):
return HttpResponse('')
#settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'app.middlewares.M',
)
#middlewares.py
class M(object):
def process_request(self, request):
request.session['a']='a'
Django adds a row to session table in db on every request. Why?
UPD: I'm still confused. I've made a github project for that question: https://github.com/vinograd19/django-session-problem/ You can find out my code there and run it on your machine
Upvotes: 2
Views: 1658
Reputation: 616
Your custom middleware M is modifying the session dictionary on every single request (Writing your own middleware):
process_request() is called on each request, before Django decides which view to execute.
Even though you are modifying the session on every request, there should only be one row for every user (same visitor on the same browser). If the same visitor makes multiple requests, his corresponding session row should be updated on every request (because of your middleware 'M'). An additional row will not be created for the same visitor, but new rows are created as new visitors come to your website. From Django docs:
consider what happens with the database backend. When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted. A similar process happens with the file backend.
If you have found many rows in your DB sessions table, then you probably have expired sessions that need to be purged (Clearing the session store)
Django does not provide automatic purging of expired sessions. Therefore, it’s your job to purge expired sessions on a regular basis. Django provides a clean-up management command for this purpose: clearsessions. It’s recommended to call this command on a regular basis, for example as a daily cron job.
In this case, you should call the clearsessions command:
django-admin.py clearsessions
You should setup a cron job to regularly call this command and clean out expired sessions.
Upvotes: 4