Django简单访问统计

2020-04-19 | Tags: 博客搭建

今天想着给博客加个访问统计的功能,就上网找了一下,发现了一个叫django-tracking2的工具还是不错的,试用了一下。 功能比较简单,不过也满足最基本需求了。

django-tracking2

这里是django-tracking2在github上的页面,通过说明可以很快的吧django-tracking2部署好。

目前django-tracking2官方可以支持到django2.1版本,本blog用的是django2.1.8。确认版本支持后,就可以进行配置了。

下载和配置

pip install django-tracking2

然后配置一下settings.py文件,在INSTALLED_APPS中加入'tracking',

INSTALLED_APPS = (
    ...
    'tracking',
    ...
)

在MIDDLEWARE_CLASSES中加入'tracking.middleware.VisitorTrackingMiddleware',注意要加在'django.contrib.sessions.middleware.SessionMiddleware'之前。

MIDDLEWARE_CLASSES = (
    ...
    'tracking.middleware.VisitorTrackingMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
)

这样就可以加入django-tracking2的APP和用作统计功能的中间件了

然后可以在settings.py中定制一些django-tracking2配置,主页上有各项配置的详细说明:

#是否追踪ajax请求,默认False
TRACK_AJAX_REQUESTS - If True, AJAX requests will be tracked. Default is False

#是否追踪匿名用户请求, 默认True
TRACK_ANONYMOUS_USERS - If False, anonymous users will not be tracked. Default is True

#是否追踪superuser, 默认True
TRACK_SUPERUSERS - If False, users with the superuser flag set to True will not be tracked. Default is True.

#是否单独独立页面请求,默认False
TRACK_PAGEVIEWS - If True, individual pageviews will be tracked.

#需要忽略的追踪的url,默认为'favicon.ico' and 'robots.txt',另外对于静态文件(js,css等)不应该通过django访问,因此也不会被追踪
TRACK_IGNORE_URLS - A list of regular expressions that will be matched against the request.path_info (request.path is stored, but not matched against). If they are matched, the visitor (and pageview) record will not be saved. Default includes 'favicon.ico' and 'robots.txt'. Note, static and media are not included since they should be served up statically Django's static serve view or via a lightweight server in production. Read more here

#需要忽略追踪的页面请求返回值
TRACK_IGNORE_STATUS_CODES - A list of HttpResponse status codes that will be ignored. If the HttpResponse object has a status_code in this blacklist, the pageview record will not be saved. For example,TRACK_IGNORE_STATUS_CODES = [400, 404, 403, 405, 410, 500]

#是否追踪referring site???,默认False
TRACK_REFERER - If True, referring site for all pageviews will be tracked. Default is False

#是否追踪所有url请求串???默认False
TRACK_QUERY_STRING - If True, query string for all pageviews will be tracked. Default is False

这边的话我开启了

TRACK_PAGEVIEWS = True

可以同时追踪用户对不同页面的访问情况。

TRACK_IGNORE_URLS = [
    r'^admin/*',
        r'^markdownx/*',
        r'^tracking/*',
        r'^static/*',
        ]

可以忽略对一些无效url访问的统计。

展示

最后在urls.py中加入一个简单的统计页面规则就可以看到用户的访问情况了

urlpatterns = patterns('',
    ...
    url(r'^tracking/', include('tracking.urls')),

    #在django2中可以改为
    path('tracking/', include('tracking.urls')),
    ...
)

这个时候作为superuser或者user登入后访问/tracking/就可以看到统计结果了

统计结果