Clearing sessions in django_session table without

2020-07-06 05:41发布

I am working on sessions in Django.

By default, django stores sessions in django_session, I found out there is no way to purge sessions.

Though clearsessions can be used to delete rows. It is also recommended to run this as a cron job. But doing this means logging out all logged-in users, right?

Is this the right way to do it?

标签: python django
3条回答
Luminary・发光体
2楼-- · 2020-07-06 05:48
  1. Django 1.6 or Above

    python manage.py clearsessions

  2. Django 1.5 or lower

    python manage.py cleanup

  3. From Django Shell

    from django.contrib.sessions.models import Session
    Session.objects.all().delete()
    
  4. django-session-cleanup cronJob

  5. clearing session in logout( based on session key present in request)

from django.contrib.sessions.models import Session  
session_key = request.data['sessionKey']
session = Session.objects.get(session_key=session_key)
Session.objects.filter(session_key=session).delete()
Session.objects.all().delete()
查看更多
甜甜的少女心
3楼-- · 2020-07-06 05:50

The Django documentation states (emphasis from me):

Clearing the session store

As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, the django_session database table will grow. If you’re using the file backend, your temporary directory will contain an increasing number of files.

To understand this problem, 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.

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.

Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.

Found this link in Abid A's answer.

The clearsessions command

Can be run as a cron job or directly to clean out expired sessions.

So it won't log off every user.

As mentioned by Kevin Christopher Henry in a comment and in the other possible duplicate of your question flagged by e4c5.

查看更多
乱世女痞
4楼-- · 2020-07-06 06:04

The newer versions of Django allow:

request.session.clear()
查看更多
登录 后发表回答