1. 程式人生 > >頁面瀏覽統計之(一) hitcount

頁面瀏覽統計之(一) hitcount

方式 needed ng- uri 對象的訪問 ews pip 返回 app

轉:http://www.codingsoho.com/zh/blog/component-hitcount/

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> 

頁面瀏覽統計之(一) hitcount