django-装饰器实现PV统计
1.models层建立统计表####
# 每日访问量统计
class Statistics(models.Model):
pv = models.IntegerField(default=0)
uv = models.IntegerField(default=0)
date = models.CharField(max_length=200)
class Meta:
verbose_name = '网站统计信息'
verbose_name_plural = '网站统计信息'
def __unicode__(self):
return self.date
2.decorator.py建立装饰器函数####
实现每次调用view试图函数前数据库字段先自加1
#!/usr/bin/env python
# -*- coding=utf-8 -*-
##################################
from models import Statistics
import time
def pvCount(func):
def wrapper(request, *args, **kwargs):
dateObj_list = Statistics.objects.filter(date=time.strftime('%Y-%m-%d'))
count = dateObj_list.count()
if count == 0:
Statistics.objects.create(pv=1,uv=0,date=str(time.strftime('%Y-%m-%d')))
else:
todayObj = Statistics.objects.get(date=str(time.strftime('%Y-%m-%d')))
todayObj.pv += 1
todayObj.save()
return func(request, *args, **kwargs)
return wrapper
3.view试图导入装饰器函数,并调用####
from decorator import pvCount
@pvCount
def index(request):
count = models.NewMachine.objects.all().count()
phycount = models.PhysicalHost.objects.all().count()
ret = dict()
ret['count'] = count
ret['phycount'] = phycount
# return HttpResponse('123456')
#logger.error("level info test")
return render_to_response('app/pages/index.html', ret)
原创:做时间的朋友