且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

修改不同Django用户的会话数据

更新时间:2023-11-27 23:17:46

p> tldr; 查询会话模型,然后通过 SessionStore 修改匹配的会话。 p>

您的问题有两方面,如何获取用户的会话,以及如何修改任意会话的数据(可能在视图之外)。



获取所有登录用户会话



由于会话数据以编码形式存储,所以建议获取所有未过期的会话,迭代他们,解码数据并检查是否与用户相关联。收集匹配的会话密钥以便稍后执行。

  from datetime import datetime 

>&gt ; session = Session.objects.exclude(expire_date__lte = datetime.now())
#[< Session:Session对象>,< Session:Session对象>]

>> &GT;如果s.get_decoded()。get('_ auth_user_id'),则会记录s_ession_key for s会话
#[u'qu1ir36jjvgbq2koqfa37b9hw1kb3ssu']



修改视图之外的会话



尽管该方案没有明确说明,文档提到如何访问会话,而不需要code>请求上下文。基本上, SessionStore 必须用于修改会话(反过来会将新数据存储在 Session

 从django.contrib.sessions.backends.db导入SessionStore 

#在会话存储中查找我们的会话
session_key在logged_in中:
s = SessionStore(session_key = session_key)
s ['test'] = True
s.save()
s.modified
#True


This may not be possible, but when certain conditions happen, I'd like to modify the session data of certain logged in users (flagging that some extra logic needs to run the next time they load a page).

Is there a way to access the session of a user by their ID?

tldr; Query Session model, then modify matching sessions via SessionStore.

Your question is twofold, how to get session of a user, and how to modify data of arbitrary sessions (possibly outside of view).

Get all logged in user sessions

Since the session data is stored in an encoded form, I suggest getting all non-expired sessions, iterate over them, decode the data and check if associated with a user. Collect matching session keys to act on later.

from datetime import datetime

>>> sessions = Session.objects.exclude(expire_date__lte=datetime.now())
# [<Session: Session object>, <Session: Session object>]

>>> logged_in = [s.session_key for s in sessions if s.get_decoded().get('_auth_user_id')]
# [u'qu1ir36jjvgbq2koqfa37b9hw1kb3ssu']

Modify sessions outside of view

Although the scenario is not explicitely stated, the docs do mention how to access sessions, without request context. Basically, SessionStore must be used to modify the session (which in turn will store the new data in Session)

from django.contrib.sessions.backends.db import SessionStore

# look up our sessions in session store
for session_key in logged_in:
    s = SessionStore(session_key=session_key)
    s['test'] = True
    s.save()
    s.modified
    # True