Modify session data of different Django user

ε祈祈猫儿з 提交于 2019-12-04 18:06:28

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!