从所有用户删除会话密钥 [英] Delete session key from all users

查看:115
本文介绍了从所有用户删除会话密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户登录一些细节保存到会话中时,可以使用key ='user_settings'

当系统内部发生一些更新时,我需要循环通过所有用户删除每个用户会话中的user_settings密钥。这样我就会触发从数据库中加载新的细节。



如何循环遍历所有会话并从每个会话中删除密钥?

解决方案

循环



即使你的网站只有几千个用户,你可能会发现django_sessions表中有几百个条目。如果会话没有被清理,就会发生这种情况。如果循环使用它们并删除会话条目,您将发现该过程非常慢。甚至100个会话将导致执行100个查询。



使用会话模型。



您可以申请过滤器 django.contrib.sessions.models.Session 就像在任何其他型号上一样。因此,以下查询将一次性清除所有会话。

 从django.contrib.sessions.models导入会话
Session.objects.all()。delete()

您可以选择省略一些用户

  Session.objects.filter(session_key__in = [...])。delete()

它不涉及数据检索或循环。



./管理。 py



您还可以使用 ./ manage.py clearsessions 清理已过期的会话。



在数据库级别



也许禁食是删除所有的会话用sql查询。如果检索和删除将非常慢,并涉及数百万次查询。



在支持TRUNCATE的数据库

  TRUNCATE django_session 

对于那些不

  DELETE FROM django_session 

最后,请记住,会话会不时到期,因此清除整个会话对象并不是很多伤害,而不是删除特定的密钥。


When a user logs in some details are saved to the session, lets say using key='user_settings'

When some updates happens within the system I need to loop through all users and delete the 'user_settings' key from each users session. That way I will trigger loading the details fresh from the database.

How can I loop through all sessions and remove the key from each of the sessions?

解决方案

Looping

Even if your site has only a few thousand users, you might find that the django_sessions table has a few million entries in it. This happens if the sessions haven't been cleaned up. If you loop through them and delete the session entries you will find the process to be very slow. Even 100 sessions would result in a 100 queries being executed.

Using the Session Model.

You can apply filters on django.contrib.sessions.models.Session just as you would on any other model. Thus the following query would clear out all the sessions in one go.

 from django.contrib.sessions.models import Session
 Session.objects.all().delete()

You could choose to leave out some users

 Session.objects.filter(session_key__in = [ ... ]).delete()

It does not involve a data retrieval or looping.

./manage.py

You could also use ./manage.py clearsessions to clean up expired sessions. Unexpired ones will be retained.

At the database level

Perhaps the fasted is to delete all the sessions is with an sql query. Where as retrieval and delete will be very very slow and involves millions of queries.

In the case of databases that support TRUNCATE

TRUNCATE django_session

For those that don't

DELETE FROM django_session

Lastly bear in mind that sessions do expire from time to time, so there isn't a lot of harm in clearing an entire session object instead of just deleting a specific key

这篇关于从所有用户删除会话密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆