页面浏览统计之(二) tracking

转:http://www.codingsoho.com/zh/blog/component-tracking/

django-tracking是一个简单的访客记录的应用

前言

本文环境:

Python 2.7.10
Django 1.11

安装

github主页 https://github.com/bashu/django-tracking

django-tracking 0.4.1 版本太老

问题

init里不能import listeners,否则User访问时报错app未导入

查看github上的源代码,并没有这一句,所以去掉应该不会对清理产生影响。这个项目有点乱,github和pypi上有的乱码新旧不一致

File "E:\Computer\virtualenv\iblog\csblog\tracking\__init__.py", line 1, in <module>
  import listeners
File "E:\Computer\virtualenv\iblog\csblog\tracking\listeners.py", line 9, in <module>
  from tracking.models import UntrackedUserAgent, BannedIP
File "E:\Computer\virtualenv\iblog\csblog\tracking\models.py", line 11, in <module>
  from django.contrib.auth.models import User
File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
  from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
  class AbstractBaseUser(models.Model):
File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\db\models\base.py", line 110, in __new__
  app_config = apps.get_containing_app_config(module)
File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config
  self.check_apps_ready()
File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready
  raise AppRegistryNotReady("Apps aren‘t loaded yet.")
ango.core.exceptions.AppRegistryNotReady: Apps aren‘t loaded yet.

GEOIP支持

from django.contrib.gis. utilsimport HAS_GEOIP

修改为

from django.contrib.gis.geoip import HAS_GEOIP

django新版本位置变了,而且目前是不支持geoip的

MiddlewareMixin

代码直接使用会报错,需要将中间件类的基类改为MiddlewareMixin

Traceback (most recent call last):
  File "..\env\Lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "..\env\Lib\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run
    handler = self.get_handler(*args, **options)
  File "..\env\Lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super(Command, self).get_handler(*args, **options)
  File "..\env\Lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler
    return get_internal_wsgi_application()
  File "..\env\Lib\site-packages\django\core\servers\basehttp.py", line 46, in get_internal_wsgi_application
    return get_wsgi_application()
  File "..\env\Lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application
    return WSGIHandler()
  File "..\env\Lib\site-packages\django\core\handlers\wsgi.py", line 153, in __init__
    self.load_middleware()
  File "..\env\Lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware
    mw_instance = middleware(handler)
TypeError: object() takes no parameters

需要在middleware.py里修改

try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    MiddlewareMixin = object

class VisitorTrackingMiddleware(MiddlewareMixin):

配置

在settings文件里添加APP

    INSTALLED_APPS = (
        ‘django.contrib.admin‘,
        ‘django.contrib.auth‘,
        ‘django.contrib.contenttypes‘,
        ‘django.contrib.sessions‘,
        ‘django.contrib.sites‘,
        ...
        ‘tracking‘,
        ...
    )

运行manage.py migrate同步数据库

添加middleware,他们分别提供下面功能

  • tracking.middleware.VisitorTrackingMiddleware 访客跟踪,必须在AuthenticationMiddleware后面,这样才能访问request.user
  • tracking.middleware.VisitorCleanUpMiddleware 访客自动清理,它将会自动从数据库中清除掉过去的访问者。新版本代码实现里去掉了功能,实际是一个空类,需要研究一下。该应用提供命令来清理历史访客记录。
  • tracking.middleware.BannedIPMiddleware IP黑名单,建议放在最前面,这样那些被禁止的用户也不会在其他的middleware里运行
MIDDLEWARE = [
    ‘tracking.middleware.BannedIPMiddleware‘,
    #
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
    #
    ‘tracking.middleware.VisitorTrackingMiddleware‘,
    ‘tracking.middleware.VisitorCleanUpMiddleware‘,

]

注意:如果在cms项目中使用的话,记得把它放在cms的middleware前面,否则报错No module named LanguageCookieMiddlewaretracking.middleware

这个跟cms项目安装的要求是一致的,避免URL路由匹配问题。

Traceback (most recent call last):
  File "env\Lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "env\Lib\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run
    handler = self.get_handler(*args, **options)
  File "env\Lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super(Command, self).get_handler(*args, **options)
  File "env\Lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler
    return get_internal_wsgi_application()
  File "env\Lib\site-packages\django\core\servers\basehttp.py", line 46, in get_internal_wsgi_application
    return get_wsgi_application()
  File "env\Lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application
    return WSGIHandler()
  File "env\Lib\site-packages\django\core\handlers\wsgi.py", line 153, in __init__
    self.load_middleware()
  File "env\Lib\site-packages\django\core\handlers\base.py", line 80, in load_middleware
    middleware = import_string(middleware_path)
  File "env\Lib\site-packages\django\utils\module_loading.py", line 20, in import_string
    module = import_module(module_path)
  File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named LanguageCookieMiddlewaretracking.middleware

正确的顺序如下

MIDDLEWARE = (
    ‘tracking.middleware.BannedIPMiddleware‘,
    ‘tracking2.middleware.VisitorTrackingMiddleware‘,
    #
    ‘cms.middleware.utils.ApphookReloadMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.locale.LocaleMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
    ‘django.contrib.sites.middleware.CurrentSiteMiddleware‘,
    #
    ‘tracking.middleware.VisitorTrackingMiddleware‘,
    ‘tracking.middleware.VisitorCleanUpMiddleware‘,
    #
    ‘cms.middleware.user.CurrentUserMiddleware‘,
    ‘cms.middleware.page.CurrentPageMiddleware‘,
    ‘cms.middleware.toolbar.ToolbarMiddleware‘,
    ‘cms.middleware.language.LanguageCookieMiddleware‘
)

确保‘django.template.context_processors.request‘已经在模板处理器中定义,老的名字是django.core.context_processors.request

这样处理器能够保证request对象可以访问模板,该应用使用request对象来判断当前用户在查看哪个页面。

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [os.path.join(BASE_DIR,‘templates‘)],
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]

另外,如果你想看看你的访问者都来自哪儿,就需要用到map特性。它使用的是google技术,咱又用不了,就不研究了,有兴趣直接去github看。

使用

要显示当前的模板访问的活跃用户,首先在模板头添加{% load tracking_tags %},然后添加下面代码

To display the number of active users there are in one of your templates, make sure you have {% load tracking_tags %} somewhere in your template and do something like this:

{% visitors_on_site as visitors %}
<p>
    {{ visitors }} active user{{ visitors|pluralize }}
</p>

如果想看看多少人正在看同一页

If you also want to show how many people are looking at the same page:

{% visitors_on_page as same_page %}
<p>
    {{ same_page }} of {{ visitors }} active user{{ visitors|pluralize }}
    {{ same_page|pluralize:"is,are" }} reading this page
</p>

If you don‘t want particular areas of your site to be tracked, you may define a list of prefixes in your settings.py using theN O_TRACKING_PREFIXES. For example, if you didn‘t want visits to the/family/ section of your website,set NO_TRACKING_PREFIXES to[‘/family/‘].

If you don‘t want to count certain user-agents, such as Yahoo!‘s Slurp and Google‘s Google bot, you may add keywords to your visitor tracking in your Django administration interface. Look for "Untracked User-Agents" and add a keyword that distinguishes a particular user-agent. Any visitors with the keyword in their user-agent string will not be tracked.

默认,活跃用户统计十分钟内的访问者,你也可以通过修改settings里的TRACKING_TIMEOUT改到你想改的任意值

By default, active users include any visitors within the last 10 minutes. If you would like to override that setting, just set TRACKING_TIMEOUT to however many minutes you want in your settings.py.

每24小时,系统自动清理访问内容,你可以通过覆盖TRACKING_CLEANUP_TIMEOUT这个值来修改

For automatic visitor clean-up, any records older than 24 hours are removed by default. If you would like to override that setting, set TRACKING_CLEANUP_TIMEOUT to however many hours you want in your settings.py.

原文地址:https://www.cnblogs.com/2dogslife/p/9735952.html

时间: 2024-10-23 20:04:34

页面浏览统计之(二) tracking的相关文章

实现页面浏览统计

<?php session_start(); $server = '127.0.0.1'; $username = 'root'; $password = ''; $conn = mysql_connect($server, $username, $password); $e = mysql_select_db('test',$conn); mysql_query("SET NAMES UTF8"); //$sql = "select * from tongji&quo

页面浏览统计之(一) hitcount

转:http://www.codingsoho.com/zh/blog/component-hitcount/ hit counter是用来计数模型对象的访问次数的. Django hit counter application that tracks the number of hits/views for chosen objects. https://github.com/thornomad/django-hitcount 安装 pip install django-hitcount 参考

php统计网站 / html页面 浏览访问次数程序

本文章来给大这介绍了php自己写的一些常用的网站统计代码写法,用无数据库的与使用数据库及html静态页面浏览资次数统计代码,大家可进入参考. 实例1 直接使用txt文件进行统计的代码 <?php session_start(); //定义session,同一IP登录不累加 $filepath = 'count.txt'; //count.txt 统计次数 if($_SESSION['temp'] == ''){ //判断$_SESSION[temp]的值是否为空,其中的temp为自定义的变量 i

并发页面访问量统计简单实现

页面访问量统计,可能在上学的时候就讲过如何简单实现,例如在servletContext中保存一个页页面访问次数,然后每访问一次加1:或者每访问一次就把操作记录保存到数据库,这样的处理方式,做做实验就算了,在实际应用中这样应用对系统性能影响特别大. 第一种方式,因为页面访问次数属于一个公共变量,在对公共变量进行修改的时候,往往需要加上同步锁:同步锁会导致访问速度明显变慢:第二种方式也一样,而且频繁访问数据库也不是一种合理的方式. 前不久,我一个朋友要我帮他们写一个简单的页面统计代码.1.需求是保存

UIWebView页面的控制(二)

1.UIWebView的内容控制的属性/方法列表 loading属性               确认当前页面是否在读入中 canGoForward属性   确认goForward  方法是否可执行,可执行为yes: canGoBack属性        确认goBack  方法是否可执行,可执行为yes: goBack方法               返回前一个页面 goForword方法          进入下一个页面 reload方法                 重新读入当前页 st

词频统计-功能二

一.完成一个小程序 今天的任务是处理一本英文小说.我处理的英文小说是<war and peace> 本想着用多线程来解决的,发现看书还不是太懂,并不能真正动手编程. 我在编程的过程中主要遇到了以下两个问题: 1.在对整个英文小说进行单词总数统计遇见困难. 2.字符串数组的空字符串处理问题.因为我开始用空格来代替标点等不是英文单词来进行对单词分割,其中用到了正则表达式,后来统计对单词出现频数时,发现空格竟然排第一名,有4万多空格. 最终我的处理方式是使用List泛型集合的ForEach方法循环获

查找页面报错(二)

查找页面报错 服务器未发送任何数据,因此无法载入该网页. 错误 324 (net::ERR_EMPTY_RESPONSE):服务器已断开连接,且未发送任何数据. 查找页面报错(二)

优化页面访问速度(二) ——数据库优化

优化页面访问速度(二) ——数据库优化 一.概述 数据库优化,主要包括数据表设计.索引.sql语句.表拆分.数据库服务器架构等方向的优化. 二.数据库设计 在建表的时候,就需要考虑到将来的使用场景,尽量在建表初期就设计好. 1.存储引擎 Mysql常被提到的存储引擎就是InnoDB和MySIAM,其实现在主要都在用InnoDB了.两者的区别: InnoDB支持事务,索引和数据存在一个文件,主键查询速度快(主键就是索引B+树的叶子节点,而数据就绑定在叶子节点),行级锁,支持外键,恢复起来较快. M

JS-改变页面的颜色(二)

需求:点击页面的按钮,改变页面的颜色 思路:一先画出最简单的页面,二想办法获取页面的body节点,三想办法修改body节点的背景颜色属性,四通过一个方法获取随机的颜色值           和第一个例子(JS-改变页面的颜色(一))相比仅仅是改变了生成颜色值的思路 简单的代码片段如下所示: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Change P