修改不同Django用户的会话数据 [英] Modify session data of different Django user

查看:118
本文介绍了修改不同Django用户的会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是不可能的,但是当某些情况发生时,我想修改某些登录用户的会话数据(标记下一次加载页面时需要一些额外的逻辑)。



有没有办法通过他们的ID访问用户的会话?

解决方案

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

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



获取所有登录用户会话



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

  from datetime import datetime 

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

>> >如果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

这篇关于修改不同Django用户的会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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