且构网

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

如何查找django的会话为一个特定的用户?

更新时间:2023-11-27 23:30:58

修改 django_session中表中添加一个明确的 USER_ID 可以让生活变得更加简单。假设你做(或类似的东西),这里是改写(munging)的东西根据自己的喜好四种方法:

Modifying the django_session table to add an explicit user_id can make life a lot easier. Assuming you do that (or something similar), here are four approaches to munging things to your liking:

叉子 django.contrib.session code。我知道,我知道,这是一个可怕的建议。但它只有500线,包括所有的后端和减去测试。这是pretty简单的破解。这只是如果你准备做事情一些严重清理的***路线。

Fork the django.contrib.session code. I know, I know, that's a horrible thing to suggest. But it's only 500 lines including all backends and minus the tests. It's pretty straightforward to hack. This is the best route only if you are going to do some serious rearranging of things.

如果您不想叉,你可以尝试连接到 Session.post_save 信号和munge那里。

If you don't want to fork, you could try connecting to the Session.post_save signal and munge there.

或者你可以猴补丁 contrib.session.models.Session.save()。只是包装现有的方法(或创建一个新的),突破/合成任何你需要的值,并将其存储在您的新域,然后超(会话,个体经营).save()

Or you could MonkeyPatch contrib.session.models.Session.save(). Just wrap the existing method (or create a new one), breakout/synthesize whatever values you need, store them in your new fields, and then super(Session, self).save().

然而,这样做的另一种方式是把2(是,二)中间件类 - 一前一后的 SessionMiddleware 在你的 settings.py 的文件。这是因为中间件被处理的方式。在 SessionMiddleware 中列出的人会得到的,在入站请求,与会话的请求已经连接到它。上市前可以做任何处理的响应和/或变更/重新保存会话。

Yet another way of doing this is to put in 2 (yes, two) middleware classes -- one before and one after SessionMiddleware in your settings.py file. This is because of the way middleware is processed. The one listed after SessionMiddleware will get, on the inbound request, a request with the session already attached to it. The one listed before can do any processing on the response and/or change/resave the session.

我们用这最后的技术变化来创建搜索引擎蜘蛛伪会议给他们的会员制通常是材料的特殊访问。我们也检测内部链接,其中 REFERER 字段是从相关的搜索引擎,我们给用户完全访问的一篇文章。

We used a variation on this last technique to create pseudo-sessions for search engine spiders to give them special access to material that is normally member-only. We also detect inbound links where the REFERER field is from the associated search engine and we give the user full access to that one article.

更新:

我的回答是现在很古老,但它仍然是大部分正确的。见@ Gavin_Ballard的下面更近的答案(2014年9月29日)为另一种方法解决这个问题。

My answer is now quite ancient, although it still is mostly correct. See @Gavin_Ballard's much more recent answer (9/29/2014) below for yet another approach to this problem.