Modify session data of different Django user

最后都变了- 提交于 2019-12-21 23:05:16

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/29656333/modify-session-data-of-different-django-user

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