Django项目部署 - 访问量统计和页面点击数

http://blog.csdn.net/pipisorry/article/details/47396311

下面是在模板中做一个简单的页面点击数统计、model阅读量统计、用户访问量统计的方法

简单的模板页面计数的实现

模板中设置:

<li>您是第{{count}}个访问本站的朋友</li>
<li>访问时间:{{time}}</li>

view.py中

def getTime():#获取当前时间
    import time
    return time.ctime()

def getCount():#获取访问次数
    countfile  = open(‘count.dat‘,‘a+‘)#以读写形式打开记录计数的文件
    counttext = countfile.read()
    try:
        count = int(counttext)+1
    except:
        count = 1
    countfile.seek(0)
    countfile.truncate()#清空文件
    countfile.write(str(count))#重新写入新的访问量
    countfile.flush()
    countfile.close()
    return count

def myHelloWorld(request):
    time = getTime()
    count = getCount()
    para = {"count":count,"time":time}
    ...

这样每次访问时都会调用myHelloWorld函数,读取count值并+1操作

[使用模板做一个站点访问计数器]

http://blog.csdn.net/pipisorry/article/details/47396311

model对象的计数器实现

Django hit counter application that tracks the number of hits/views for chosen objects.

hit counter是用来计数model对象的访问次数的。

安装django-hitcount:

pip install django-hitcount

Settings.py

Add django-hitcount to your INSTALLED_APPS, enableSESSION_SAVE_EVERY_REQUEST:

# settings.py
INSTALLED_APPS = (
    ...
    ‘hitcount‘
)
# needed for django-hitcount to function properly
SESSION_SAVE_EVERY_REQUEST = True

Urls.py

urls.py中加入

# urls.py
urlpatterns = patterns(‘‘,
    ...
    url(r‘hitcount/‘, include(‘hitcount.urls‘, namespace=‘hitcount‘)),
)

View the additional settings section for more information.

Template Magic

Django-hitcount comes packaged with a jQuery implementation that works out-of-the-box to record the
Hits
to an object (be it a blog post, poll, etc). To use thejQuery
implementation
you can either include the app’s script file (as the documentation below shows) or to copy-paste the script into your own jQuery code. Of course: you could also implement this without relying on jQuery.

在需要的模板最开始地方加入loading hitcount tags

{% load hitcount_tags %}

Recording a Hit

If you want to use the jQuery implementation in your project, you can add the Javascript file to your template like so:

{% load staticfiles %}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="{% static ‘hitcount/hitcount-jquery.js‘ %}"></script>

Then, on your object detail page (blog, page, poll, etc) you inject the needed javascript variables:

# use default insertion method for hitcount-jquery.js:
{% insert_hit_count_js_variables for object %}

# or you can use a template variable to inject as you see fit
{% get_hit_count_js_variables for object as hitcount %}
({ hitcount.ajax_url }}
{{ hitcount.pk }}

Displaying Hit Information

You can retrieve the number of hits for an object many different ways:

# Return total hits for an object:
{% get_hit_count for [object] %}

# Get total hits for an object as a specified variable:
{% get_hit_count for [object] as [var] %}

# Get total hits for an object over a certain time period:
{% get_hit_count for [object] within ["days=1,minutes=30"] %}

# Get total hits for an object over a certain time period as a variable:
{% get_hit_count for [object] within ["days=1,minutes=30"] as [var] %}

[Installation and Usage]

[example project]

[django-hitcount]

http://blog.csdn.net/pipisorry/article/details/47396311

页面的用户访问量统计

django-tracking keeps track of visitors to Django-powered Web sites. It also offers basic blacklisting capabilities.

安装django-tracking

pip install django-tracking

Note:会出错: no module named listeners

配置

First of all, you must add this project to your list of INSTALLED_APPS insettings.py:

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

Run manage.py syncdb. This creates a few tables in your database that arenecessary for operation.

Depending on how you wish to use this application, you have a few options:

Visitor Tracking

Add tracking.middleware.VisitorTrackingMiddleware to yourMIDDLEWARE_CLASSES in
settings.py. It must be underneath theAuthenticationMiddleware, so that
request.user exists.

Automatic Visitor Clean-Up

If you want to have Django automatically clean past visitor information outyour database, put
tracking.middleware.VisitorCleanUpMiddleware in yourMIDDLEWARE_CLASSES.

IP Banning

Add tracking.middleware.BannedIPMiddleware to your MIDDLEWARE_CLASSESin
settings.py. I would recommend making this the very first item inMIDDLEWARE_CLASSES so your banned users do not have to drill through anyother middleware before Django realizes they don‘t belong on your site.

Visitors on Page (template tag)

Make sure that django.core.context_processors.request is somewhere in yourTEMPLATE_CONTEXT_PROCESSORS tuple. This context processor makes therequest object accessible to your templates. This application uses therequest
object to determine what page the user is looking at in a templatetag.

Active Visitors Map

If you‘re interested in seeing where your visitors are at a given point intime, you might enjoy the active visitor map feature. Be sure you have added aline to your main URLconf, as follows:

from django.conf.urls.defaults import *

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

Next, set a couple of settings in your settings.py:

  • GOOGLE_MAPS_KEY: Your very own Google Maps API key
  • TRACKING_USE_GEOIP: set this to True if you want to see markers onthe map
  • GEOIP_PATH: set this to the absolute path on the filesystem of yourGeoIP.dat or
    GeoIPCity.dat or whatever file. It‘s usually somethinglike /usr/local/share/GeoIP.dat or
    /usr/share/GeoIP/GeoIP.dat.
  • GEOIP_CACHE_TYPE: The type of caching to use when dealing with GeoIP data:
    • 0: read database from filesystem, uses least memory.
    • 1: load database into memory, faster performance but uses morememory.
    • 2: check for updated database. If database has been updated, reloadfilehandle and/or memory cache.
    • 4: just cache the most frequently accessed index portion of thedatabase, resulting in faster lookups than
      GEOIP_STANDARD, but lessmemory usage than GEOIP_MEMORY_CACHE - useful for larger databasessuch as GeoIP Organization and GeoIP City. Note, for GeoIP Country,Region and Netspeed databases,
      GEOIP_INDEX_CACHE is equivalent toGEOIP_MEMORY_CACHE.
      default
  • DEFAULT_TRACKING_TEMPLATE: The template to use when generating thevisitor map. Defaults to
    tracking/visitor_map.html.

When that‘s done, you should be able to go to /tracking/map/ on your site(replacing
tracking with whatever prefix you chose to use in your URLconf,obviously). The default template relies upon jQuery for its awesomeness, butyou‘re free to use whatever you would like.

Usage

To display the number of active users there are in one of your templates, makesure you have
{% load tracking_tags %} somewhere in your template and dosomething 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 alist of prefixes in your
settings.py using the NO_TRACKING_PREFIXES. Forexample, 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 andGoogle‘s Googlebot, you may add keywords to your visitor tracking in yourDjango administration interface. Look for "Untracked User-Agents" and add akeyword that distinguishes a particular
user-agent. Any visitors with thekeyword in their user-agent string will not be tracked.

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

For automatic visitor clean-up, any records older than 24 hours are removed bydefault. If you would like to override that setting, setTRACKING_CLEANUP_TIMEOUT to however many hours you want in yoursettings.py.

[django-tracking] from:http://blog.csdn.net/pipisorry/article/details/47396311

ref:在Django中实现一个高性能未读消息计数器

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-12 11:38:28

Django项目部署 - 访问量统计和页面点击数的相关文章

django项目自定义错误显示页面

当把django项目部署到正式环境的时候,需要把settings里的debug设置关闭,这时候就需要自定义一些错误显示页面了 版本django1.11 步骤: 1 设置settings文件 DEBUG = False ALLOWED_HOSTS = [*] 2 配置urls文件 handler403 = views.permission_denied handler404 = views.page_not_found handler500 = views.page_error 3 配置views

Django 项目部署

Django 项目部署 原文地址:https://www.cnblogs.com/guozepingboke/p/10844060.html

CentOS 7 下Django项目部署教程(基于uwsgi和Nginx)

本文主要介绍如何在Linux平台上部署Django相关项目,关于Django项目的部署在互联网论坛上有很多的资料,笔者在查阅众多资料并经过实践后发现结果并不如意(或多或少总是遇到一些问题,往往与资料的预期不相符).在浏览了许多资料后笔者整理得出了部署Django项目的一般性方法,部署的方法有很多种,在此笔者选择了较为常用的基于uwsgi和Nginx的部署方案. 一.前提准备 部署前主要是需要做一些与服务器相关的准备工作,本次教程的服务器采用了阿里云的 CentOS 7.3 64位,当然作为资料学

(转) 解决django项目部署到nginx+uwsgi服务器后 admin页面样式消失的问题

原贴地址:https://blog.csdn.net/qq_42571805/article/details/80862455 摘要 uwsgi为主要服务器,nginx为反向代理服务器部署完成之后发现django后台admin访问时无样式 解决方法如下 1.先打开django项目中settings.py文件(/blog/settings.py),添加STATIC_ROOT = ‘/home/blog/static/’ 2.打开nginx配置文件nginx.conf,添加如下图红色框中内容 3.运

django项目部署上线

前言 完善的django项目上线,有很多种上线的方法,比如apache, uwsgi, nginx等.这里只介绍2种,一种是django自带的,另外一种则是nginx + uwsgi完成介绍.这里的系统环境采用的是ubantu系统, python环境采用的是python3, django环境采用1.11 一.自带的部署功能 数据从pycharm转移到ubantu中.使用xshell软件 QQ图片20180512193224.png 数据库迁移: 如果django项目中的数据是在本地的mysql中

django 项目部署在 Apache 后, 设置二级域名

上一篇文章简单说了怎么把django的项目部署到Apache上. 现在想弄个二级域名,也就是我原来有个域名 www.mysite.com,现在我想弄个 bbs.mysite.com ,该怎么做呢. 要用到 Apache 的虚拟主机配置. 其实Apache的虚拟主机之前也配置过,有时有效,有时又不好用,也不知道个所以然.这次我详细的写一下每一步都要怎么做: 第一步:开启Apache虚拟主机功能: Apache的虚拟主机功能,默认是关闭的.如果要使用这个功能,就要开启虚拟主机功能. 如同上文提到的A

Django项目部署到Apache服务器

本文讲述的是在阿里云服务器(ECS)上部署Django项目于Apache,服务器操作系统为ubuntu,公网Ip地址为123.56.30.151. 将Django部署到Apache服务器的原因 Django中的runserver只是一个很简单的web服务器,启动服务器常见的方法是通过Putty执行命令.虽然调试和测试方便,然而如果关闭了Putty或者退出命令,服务就停止了,并且不能承受许多用户同时使用的负载.所以需要将Django部署到生产级的服务器,这里选择Apache. ubuntu上部署详

DJANGO项目部署到服务器上

---- 说明: 本文章来自于 http://www.pythonav.com/wupeiqi/3.html  是武沛齐老师个人博客上取的内容. 尊重老师的成果. 小白的项目部署 项目开发完毕后,需要将代码放到服务器上,这样用户才能访问.接下来我们一步一步来进行一波部署操作. 1. 简单粗暴 项目开发完毕,在部署之前需要再配置文件中将 ALLOWED_HOSTS配置设置为:当前服务器IP或*,如: ALLOWED_HOSTS = ["*",] 示例源码:猛击下载 然后将源码上传至服务器

django项目部署后静态文件收集【解决admin后台静态文件丢失】

在部署完Django项目后,进行admin后台登录发现样式丢失,后台日志显示:js和css文件丢失 解决办法: 配置settings.py如下: #DEBUG打开时,app的静态文件默认从这里读取 STATIC_URL = '/static/' #静态文件根目录,当关闭DEBUG的时候admin从STATIC_ROOT获取静态文件,同时需要配置url STATIC_ROOT = ("f:/py_workspace/DJ/proj/people/static/") #Django部署在A