转: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:Computervirtualenviblogcsblog racking\__init__.py", line 1, in <module>
import listeners
File "E:Computervirtualenviblogcsblog rackinglisteners.py", line 9, in <module>
from tracking.models import UntrackedUserAgent, BannedIP
File "E:Computervirtualenviblogcsblog rackingmodels.py", line 11, in <module>
from django.contrib.auth.models import User
File "E:Computervirtualenviblogenvlibsite-packagesdjangocontribauthmodels.py", line 4, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "E:Computervirtualenviblogenvlibsite-packagesdjangocontribauthase_user.py", line 52, in <module>
class AbstractBaseUser(models.Model):
File "E:Computervirtualenviblogenvlibsite-packagesdjangodbmodelsase.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "E:Computervirtualenviblogenvlibsite-packagesdjangoapps
egistry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "E:Computervirtualenviblogenvlibsite-packagesdjangoapps
egistry.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 "..envLibsite-packagesdjangoutilsautoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "..envLibsite-packagesdjangocoremanagementcommands
unserver.py", line 142, in inner_run
handler = self.get_handler(*args, **options)
File "..envLibsite-packagesdjangocontribstaticfilesmanagementcommands
unserver.py", line 27, in get_handler
handler = super(Command, self).get_handler(*args, **options)
File "..envLibsite-packagesdjangocoremanagementcommands
unserver.py", line 64, in get_handler
return get_internal_wsgi_application()
File "..envLibsite-packagesdjangocoreserversasehttp.py", line 46, in get_internal_wsgi_application
return get_wsgi_application()
File "..envLibsite-packagesdjangocorewsgi.py", line 14, in get_wsgi_application
return WSGIHandler()
File "..envLibsite-packagesdjangocorehandlerswsgi.py", line 153, in __init__
self.load_middleware()
File "..envLibsite-packagesdjangocorehandlersase.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.usertracking.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 "envLibsite-packagesdjangoutilsautoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "envLibsite-packagesdjangocoremanagementcommands
unserver.py", line 142, in inner_run
handler = self.get_handler(*args, **options)
File "envLibsite-packagesdjangocontribstaticfilesmanagementcommands
unserver.py", line 27, in get_handler
handler = super(Command, self).get_handler(*args, **options)
File "envLibsite-packagesdjangocoremanagementcommands
unserver.py", line 64, in get_handler
return get_internal_wsgi_application()
File "envLibsite-packagesdjangocoreserversasehttp.py", line 46, in get_internal_wsgi_application
return get_wsgi_application()
File "envLibsite-packagesdjangocorewsgi.py", line 14, in get_wsgi_application
return WSGIHandler()
File "envLibsite-packagesdjangocorehandlerswsgi.py", line 153, in __init__
self.load_middleware()
File "envLibsite-packagesdjangocorehandlersase.py", line 80, in load_middleware
middleware = import_string(middleware_path)
File "envLibsite-packagesdjangoutilsmodule_loading.py", line 20, in import_string
module = import_module(module_path)
File "D:Python27libimportlib\__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.