Modify session data of different Django user

2019-04-12 23:09发布

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条回答
干净又极端
2楼-- · 2019-04-12 23:47

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
查看更多
登录 后发表回答