Django訪问量和页面PV数统计
http://blog.csdn.net/pipisorry/article/details/47396311
以下是在模板中做一个简单的页面PV数统计、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 to an object (be it a blog post, poll, etc). To use thejQuery
Hits
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] %}
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 insettings.py. It must be underneath theAuthenticationMiddleware, so thatrequest.user exists.
Automatic Visitor Clean-Up
If you want to have Django automatically clean past visitor information outyour database, puttracking.middleware.VisitorCleanUpMiddleware in yourMIDDLEWARE_CLASSES.
IP Banning
Add tracking.middleware.BannedIPMiddleware to your MIDDLEWARE_CLASSESinsettings.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 keyTRACKING_USE_GEOIP: set this toTrueif you want to see markers onthe mapGEOIP_PATH: set this to the absolute path on the filesystem of yourGeoIP.datorGeoIPCity.dator whatever file. It's usually somethinglike/usr/local/share/GeoIP.dator/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 thanGEOIP_STANDARD, but lessmemory usage thanGEOIP_MEMORY_CACHE- useful for larger databasessuch as GeoIP Organization
and GeoIP City. Note, for GeoIP Country,Region and Netspeed databases,GEOIP_INDEX_CACHEis equivalent toGEOIP_MEMORY_CACHE.default
DEFAULT_TRACKING_TEMPLATE: The template to use when generating thevisitor map. Defaults totracking/visitor_map.html.
When that's done, you should be able to go to /tracking/map/ on your site(replacingtracking 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 yoursettings.py using theNO_TRACKING_PREFIXES. Forexample, if you didn't want visits to the/family/ section of your
website,setNO_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 setTRACKING_TIMEOUT to howevermany minutes you want in yoursettings.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
Django訪问量和页面PV数统计的更多相关文章
- 利用httpclient和多线程刷訪问量代码
缘起于玩唱吧,由于唱吧好友少,訪问量低,又不想加什么亲友团之类的,主要是太麻烦了,于是我就琢磨唱吧的訪问机制,准备用java的httpclient库来进行刷訪问量,想到动态IP反复使用就想到了用多线程 ...
- Servlet 实现訪问量的统计小案例
今天学习了Servlet的基础知识,学习了一个统计訪问量的小案例,记录一下 package cn.selevet_01; import java.io.IOException; import java ...
- HDU-1090-A+B for Input-Output Practice (II)(骗訪问量的)
A+B for Input-Output Practice (II) Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/327 ...
- 利用JS跨域做一个简单的页面訪问统计系统
事实上在大部分互联网web产品中,我们一般会用百度统计或者谷歌统计分析系统,通过在程序中引入特定的JS脚本,然后便能够在这些统计系统中看到自己站点页面详细的訪问情况.可是有些时候,因为一些特殊情况,我 ...
- Nginx 訪问日志增长暴增出现尖刀的具体分析
前言: Nginx日志里面Mobileweb_access.log增长特别大.一天上百兆.将近100W的訪问记录.依照我们眼下的规模,热点用户才500个左右.就算人人用手机app訪问 ...
- Android网络编程之使用HTTP訪问网络资源
使用HTTP訪问网络资源 前面介绍了 URLConnection己经能够很方便地与指定网站交换信息,URLConnection另一个子类:HttpURLConnection,HttpURLConnec ...
- [Nginx]用Nginx实现与应用结合的訪问控制 - 防盗链
应用场景:图片等资源须要设置权限,如:仅仅有认证过的用户才干訪问自己的图片. 解决的方法:使用Nginx的防盗链模块http_secure_link能够实现,该模块默认情况下不包括.故在安装时要加上- ...
- 设计模式之十五:訪问者模式(Visitor Pattern)
訪问者模式(Visitor Pattern)是GoF提出的23种设计模式中的一种,属于行为模式. 据<大话设计模式>中说算是最复杂也是最难以理解的一种模式了. 定义(源于GoF<De ...
- 微信訪问页面,莫名其妙刷新两次,火狐、谷歌、ie无问题
做微信刮刮卡活动,有个用户刮奖次数的限制,昨天一切正常,所以就修改了一些东西,今天再打开的时候刮奖次数第一次是1,第二次是3,第三次是5.感觉就是页面刷新了两遍. 检查前后台代码.发现一些bug就顺手 ...
随机推荐
- Android -----listView的重要属性
android:transcriptMode="alwaysScroll" android:cacheColorHint="#00000000" android ...
- Oracle 10g RAC的负载均衡配置[转载]
Oracle 10g RAC的负载均衡配置 负载均衡是指连接的负载均衡.RAC的负载均衡主要是指新会话连接到RAC数据库时,如何判定这个新的连接要连到哪个节点进行工作.在RAC中,负载均衡分为两种,一 ...
- [ HNOI 2006 ] 公路修建问题
\(\\\) \(Description\) 一个\(N\)个点\(M\)条边的图,每条边可以选择\(w_i,p_i\)两个边权之一,现求一个生成树上的最大边权最小值,要求这棵生成树上至少有\(K\) ...
- phpstorm如何配置xdebug?(hpStudy+PhpStorm+XDebug配置)
xdebug是什么? 初次接触,反复试了几次终于把这个xdebug给搞清楚了,类似于前端的控制台这样的东西,可以根据断点展示我们想要看的数据. 如何配置xdebug? 配置前说明: 1.phpStud ...
- Requirejs常用配置和应用
requirejs.require方法冲突 如果加载了多个requirejs脚本,每个requirejs会判断是否浏览器已经实现了require和define方法.如果浏览器已经自带require和d ...
- JS DOM节点(当前标签和同级、父级、子级..之间的关系)
1. 通过顶层document节点获取 1) document.getElementById(elementId) //根据id获得 2) document.getElementsByNa ...
- js 弹出div窗口 可移动 可关闭
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
- 救济金发放(The Dole Queue, UVa 133)
n(n<20)个人站成一圈,逆时针编号为1-n.有两个官员,A从1开始逆时针数,B从n开 始顺时针数.在每一轮中,官员A数k个就停下来,官员B数m个就停下来(注意有可能两个 官员停在同一个人上) ...
- (C/C++学习)6.数组指针和指针数组
说明:int (*p)[4] 和 int *p[4](数组指针和指针数组),如果你是一个初学者,也许当你看到这两个名词的时候,已经懵了.其实,只要你理解了其中的含义.这两个名词对你来说会相当简单并且很 ...
- node.js开发环境配置
node.js是什么 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...