Django - 检测会话的开始和结束 [英] Django - detect session start and end

查看:113
本文介绍了Django - 检测会话的开始和结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以帮助我。



我正在我网站的主页上实现在线用户数计数器。我记得在ASP的糟糕的旧时代,我以前能够通过session.onstart和session.onend来保持一个柜台。



如何在Django中执行?



干杯



Rich

解决方案

django信号非常方便:

 #这是一个模型来自django.db.models.signals的.py文件
从django.contrib.sessions.models导入pre_delete
导入会话

def sessionend_handler(sender,** kwargs):
#清理会话(temp)数据
打印会话%s结束%kwargs.get('instance')。session_key

pre_delete.connect(sessionend_handler,sender = Session)

如果用户没有点击,您需要删除会话限制,因为他们可以保留在数据库中最常见的注销。只需添加一个cron:

  * / 5 * * * * djangouser /usr/bin/python2.5 / home / project / manage.py cleanup 

我通常会将其添加到我的manage.py中,以方便settings.py路径查找:

  import sys 
import os
BASE_DIR = os.path.split(os.path .abspath(__ file __))[0]
sys.path.insert(0,BASE_DIR)

SESSION_EXPIRE_AT_BROWSER_CLOSE 工作,但只影响客户端cookie,而不是服务器活动会话IMHO。


I hope someone can help me with this.

I am trying implement a 'number of users online' counter on the home page of my site. I remember in the bad old days of ASP I used to be able to keep a counter going with a session.onstart and session.onend.

How do I do it in Django?

Cheers

Rich

解决方案

django signals are very handy :

# this is in a models.py file
from django.db.models.signals import pre_delete
from django.contrib.sessions.models import Session

def sessionend_handler(sender, **kwargs):
    # cleanup session (temp) data
    print "session %s ended" % kwargs.get('instance').session_key

pre_delete.connect(sessionend_handler, sender=Session)

you'll need to delete your session reguraly as they can stay in the database if the user doesnt click 'logout' which the case most often. just add this to a cron :

*/5 * * * * djangouser /usr/bin/python2.5 /home/project/manage.py cleanup

also i usually add this to my manage.py for easy settings.py path find :

import sys
import os
BASE_DIR = os.path.split(os.path.abspath(__file__))[0]
sys.path.insert(0, BASE_DIR)

SESSION_EXPIRE_AT_BROWSER_CLOSE works but only affects client cookies, not server-actives sessions IMHO.

这篇关于Django - 检测会话的开始和结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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