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

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

https://github.com/thornomad/django-hitcount

安装

pip install django-hitcount

参考网站 http://django-hitcount.readthedocs.org/en/latest/installation.html

配置

将django-hitcount添加到INSTALLED_APPS,同时激活SESSION_SAVE_EVERY_REQUEST

settings.py

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

更多配置查看http://django-hitcount.readthedocs.org/en/latest/settings.html

视图

urls.py中加入

urlpatterns = patterns('',
    ...
    url(r'hitcount/', include('hitcount.urls', namespace='hitcount')),
)

记录点击

https://django-hitcount.readthedocs.io/en/latest/installation.html#counting-hits

可以用HitCountMixin或者下面两个视图

  • HitCountJSONView: a JavaScript implementation which moves the business-logic to an Ajax View and hopefully speeds up page load times and eliminates some bot-traffic
  • HitCountDetailView: which provides a wrapper from Django’s generic DetailView and allows you to process the Hit as the view is loaded

我的实现项目里有类视图和函数视图,用到了上面的HitCountMixin和HitCountDetailView两个方法

HitCountMixin

mixin可以用于CBV类或者直接调用它的hit_count()类方法。该方法有两个参数HttpRequestHitCount对象,返回一个名字元组UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message')。 如果该次点击被记录,那么hit_counted=True,否则为False. hit_message用于指示当前点击是否被计数或忽略.

This mixin can be used in your own class-based views or you can call the hit_count() class method directly. The method takes two arguments, a HttpRequest and HitCount object it will return a namedtuple: UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message'). hit_counted will be True if the hit was counted and False if it was not. hit_message will indicate by what means the Hit was either counted or ignored.

代码样式如下

from hitcount.models import HitCount
from hitcount.views import HitCountMixin

# first get the related HitCount object for your model object
hit_count = HitCount.objects.get_for_object(your_model_object)

# next, you can attempt to count a hit and get the response
# you need to pass it the request object as well
hit_count_response = HitCountMixin.hit_count(request, hit_count)

# your response could look like this:
# UpdateHitCountResponse(hit_counted=True, hit_message='Hit counted: session key')
# UpdateHitCountResponse(hit_counted=False, hit_message='Not counted: session key has active hit')

HitCountDetailView

通过设置count_hit=TrueHitCountDetailView能够用于计算点击数的业务逻辑。

The HitCountDetailView can be used to do the business-logic of counting the hits by setting count_hit=True. See the views section for more information about what else is added to the template context with this view.

下面是该库例子里的实现

from hitcount.views import HitCountDetailView
class PostCountHitDetailView(HitCountDetailView):
    model = Post # your model goes here
    count_hit = True # set to True if you want it to try and count the hit

显示点击计数

有多种方式可实现计数显示 displaying-hits

  • Template Tags: provide a robust way to get related counts
  • Views: allows you to wrap a class-based view and inject additional context into your template
  • Models: can have a generic relation to their respective HitCount

项目中我选用了第一种方法来实现,可以避免修改后台代码。具体实现见后面

# remember to load the tags first
{% load hitcount_tags %}

# 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] %}

实例项目

TextCourse

通过hitcount记录浏览次数
from hitcount.models import HitCount
from hitcount.views import HitCountMixin

hit_count = HitCount.objects.get_for_object(node)

# next, you can attempt to count a hit and get the response
# you need to pass it the request object as well
hit_count_response = HitCountMixin.hit_count(request, hit_count)

# your response could look like this:
# UpdateHitCountResponse(hit_counted=True, hit_message='Hit counted: session key')
# UpdateHitCountResponse(hit_counted=False, hit_message='Not counted: session key has active hit')
    context = {
            'object': node,
    }
    context.update(hit_count_response._asdict())

hit_count_response._asdict()的结果就是hit_countedhit_message

显示浏览数

在需要记录点击的页面开始处加载标签

{% load hitcount_tags %}

我只需要简单计数,所以用下面就可以了

{% get_hit_count for object %}

aldryn_newsblog

这个是djangocms插件,下面通过修改原有代码将其实现。 目前还没有找到仅通过额外加代码解决的办法,现在的方案要改库,很不方便。

一种方法跟前面一样,修改文件

aldryn_newsblog\views.py

from hitcount.models import HitCount
from hitcount.views import HitCountMixin

class ArticleDetail(AppConfigMixin, AppHookCheckMixin, PreviewModeMixin,
                    TranslatableSlugMixin, TemplatePrefixMixin, DetailView):
    def get(self, request, *args, **kwargs):
        hit_count = HitCount.objects.get_for_object(self.object)
        hit_count_response = HitCountMixin.hit_count(request, hit_count)
        ...

或者我们可以用HitCountDetailView来实现,参考https://django-hitcount.readthedocs.io/en/latest/installation.html#hitcountdetailview

aldryn_newsblog\views.py

from hitcount.views import HitCountDetailView
class ArticleDetail(AppConfigMixin, AppHookCheckMixin, PreviewModeMixin,
                    TranslatableSlugMixin, TemplatePrefixMixin, HitCountDetailView, DetailView):
......
    count_hit = True

然后同样修改一下模板文件

aldryn_newsblog\includes\article.html

{% load hitcount_tags %}
        <i class="fa fa-eye" style="font-size: smaller;"> {% get_hit_count for object %} 浏览</i> 
        <i class="fa fa-clock-o" style="font-size: smaller;"> {{ article.publishing_date|date }}</i> 

评论

留言请先登录注册! 并在激活账号后留言!