• 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)
    
  • 相关阅读:
    SpringCloud 基础知识
    Spring 相关知识
    Java JDBC学习笔记
    Java JVM 相关基础知识
    ES6 块状绑定
    Docker 安装(window7)及基本命令
    Node.js 安装(Window7)及基本npm命令
    flask 模型类中relationship的使用及其参数backref的说明,
    flask中的状态保持(cookie,session)
    flask中request的属性说明
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/6553427.html
Copyright © 2020-2023  润新知