django - 确定 django 中 session 的年龄

标签 django session django-views

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

最佳答案

好的,这就是我的想法。好多了。我认为这与在 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)

关于django - 确定 django 中 session 的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211549/

相关文章:

python - 根据 django 网站上的操作显示用户上个月的进度

django - Django 更新或创建的性能优化

c# - 如何防止 session 超时

django - 如何使用 CSRF 中间件修改基于类的 View 中的文件上传处理程序?

security - 向用户公开自己的 session ID 是否不安全?

php - 如何使用 JQUERY 读取 SESSION 变量

python - Django 使用来自表单字段的变量运行 python 脚本

django - 我的 settings.py 被调用了 4 次 - 有什么想法吗?

python - Django 用户注册刚刚停止工作

django - 在自定义 500 处理程序中捕获错误文本