确定 django 中会话的年龄

发布于 2024-10-02 21:58:42 字数 28 浏览 2 评论 0原文

如何确定 django 中会话对象的年龄?

How can I determine the age of a session object in django?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

維他命╮ 2024-10-09 21:58:42

好的,这就是我的想法。好多了。我认为这与在 Session 对象上使用 post_save 一样便宜:

from django.db import models
from people.models import Member
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore


from django.db.models import *
from django.db.models.signals import post_save, pre_delete, post_init
from datetime import datetime

class SessionInfo(models.Model):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = models.DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    session = models.OneToOneField(Session)
    def age(self):
        return (datetime.now() - self.created)


def session_create_listener(instance, **kwargs):
    store = SessionStore(session_key=instance.session_key)

    if '_auth_user_id' in store:
        try:
            instance.sessioninfo
        except SessionInfo.DoesNotExist:
            sessioninfo = SessionInfo(session=instance) 
            sessioninfo.save()        

post_save.connect(session_create_listener, sender=Session)

OK, here's what I have come up with. Much better. I think this is as cheap as using post_save on a Session object is going to get:

from django.db import models
from people.models import Member
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore


from django.db.models import *
from django.db.models.signals import post_save, pre_delete, post_init
from datetime import datetime

class SessionInfo(models.Model):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = models.DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    session = models.OneToOneField(Session)
    def age(self):
        return (datetime.now() - self.created)


def session_create_listener(instance, **kwargs):
    store = SessionStore(session_key=instance.session_key)

    if '_auth_user_id' in store:
        try:
            instance.sessioninfo
        except SessionInfo.DoesNotExist:
            sessioninfo = SessionInfo(session=instance) 
            sessioninfo.save()        

post_save.connect(session_create_listener, sender=Session)
小傻瓜 2024-10-09 21:58:42

这就是我最终所做的而不是托马斯的建议。请注意,我拒绝使用接收器装饰器,因此它在 1.3 之前仍然可以工作。

(这需要认真纠正)。

from django.db import models
from people.models import Member
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore


from django.db.models import *
from django.db.models.signals import post_save, pre_delete, post_init
#from django.dispatch import receiver
from datetime import datetime

class SessionInfo(models.Model):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = models.DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    session = models.OneToOneField(Session)
    def age(self):
        return (datetime.now() - self.created)


def session_create_listener(instance, **kwargs):
    store = SessionStore(session_key=instance.session_key)

    if '_auth_user_id' in store:
        try:
            sessioninfo = SessionInfo.objects.get(session=instance)
        except SessionInfo.DoesNotExist:
            sessioninfo = SessionInfo(session=instance) 
            sessioninfo.save()
            store['anonymous'] = False
            store.save()
    else:
        try:
            store['anonymous']
        except KeyError:
            store['anonymous'] = True 
            store.save()

post_save.connect(session_create_listener, sender=Session)

我希望有人能为我纠正这个问题,因为我不相信这是最有效的方法。

首先也是最重要的,每次修改会话时,这都会增加两次额外的数据库命中(第一次尝试:sessioninfo = SessionInfo.objects.get(session=instance))。

第一个显然是在查找过程中。第二种发生在保存发生时,再次触发整个过程。

该怎么办呢?

Here's what I ended up doing instead of Thomas' suggestion. Note that I declined to use the receiver decorator so that this will still work pre 1.3.

(This needs serious correction).

from django.db import models
from people.models import Member
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore


from django.db.models import *
from django.db.models.signals import post_save, pre_delete, post_init
#from django.dispatch import receiver
from datetime import datetime

class SessionInfo(models.Model):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = models.DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    session = models.OneToOneField(Session)
    def age(self):
        return (datetime.now() - self.created)


def session_create_listener(instance, **kwargs):
    store = SessionStore(session_key=instance.session_key)

    if '_auth_user_id' in store:
        try:
            sessioninfo = SessionInfo.objects.get(session=instance)
        except SessionInfo.DoesNotExist:
            sessioninfo = SessionInfo(session=instance) 
            sessioninfo.save()
            store['anonymous'] = False
            store.save()
    else:
        try:
            store['anonymous']
        except KeyError:
            store['anonymous'] = True 
            store.save()

post_save.connect(session_create_listener, sender=Session)

I hope that somebody can correct this for me, because I cannot believe that this is the most efficient way to do this.

First and foremost, this adds TWO extra database hits (in the first try: sessioninfo = SessionInfo.objects.get(session=instance)) every time a session is modified.

The first is obviously during the lookup. The second happens when the save occurs, triggering the entire process again.

What to do instead?

没企图 2024-10-09 21:58:42

您需要挂钩来自 django.contrib.sessions.models.Session 的 post_init 信号才能收到会话开始(或结束)的通知,然后将该信息保存到您自己的应用程序中的模型中。例如

from django.contrib.sessions.models import Session
from django.db.models import *
from django.db.models.signals import post_init, pre_delete
from django.dispatch import receiver
from datetime import datetime

class SessionTimer(Session):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    def age(self):
        return (datetime.now() - self.created)

@receiver(post_init, sender=Session)
def session_create_listener(instance, **kwargs):
    created_session = instance
    timer_entry = SessionTimer(session=created_session)
    timer_entry.save()

@receiver(pre_delete, sender=Session)
def session_destroy_listener(instance, **kwargs):
    SessionTimer.objects.get(session=instance).delete() # short version

,当您需要知道会话的年龄时,请使用session.sessiontimer.age()。这将返回一个代表会话年龄的 TimeDelta 对象。

you would need to hook the post_init signal coming from django.contrib.sessions.models.Session to be notified of a session start (or end), and then save that info to a model in your own app. e.g.

from django.contrib.sessions.models import Session
from django.db.models import *
from django.db.models.signals import post_init, pre_delete
from django.dispatch import receiver
from datetime import datetime

class SessionTimer(Session):
    #note: a OneToOneField with the name 'session' has been added as part of the inheritance
    created = DateTimeField(auto_now_add=True) #joined field is auto initialized with creation time
    def age(self):
        return (datetime.now() - self.created)

@receiver(post_init, sender=Session)
def session_create_listener(instance, **kwargs):
    created_session = instance
    timer_entry = SessionTimer(session=created_session)
    timer_entry.save()

@receiver(pre_delete, sender=Session)
def session_destroy_listener(instance, **kwargs):
    SessionTimer.objects.get(session=instance).delete() # short version

hence when you need to know the age of a session, use session.sessiontimer.age(). this will return a TimeDelta object representing the age of the session.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文