Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting "page views" or "hits" when using cache

Tags:

python

django

I have a view called show_board. Inside it, among other things, I increment a field Board.views by 1 every time it is run, to count page views.

The problem is that when I use the @cache_page decorator on that view, Board.views is only going to get incremented every time a new cached view gets generated, and not every time that view is requested, like I want to.

How could I achieve this?

like image 936
flatterino Avatar asked Jun 10 '26 11:06

flatterino


1 Answers

You can actually write another decorator to achieve this.

def view_incrementer(view_func):
    """A decorator which increments board views"""

    def _wrapped(*args, **kwargs):
        # here you can increment Board.views
        # kwargs will contain URL parameters
        pk = kwargs.get('pk')
        Board.objects.filter(pk=pk).update(views=F('views')+1)
        return view_func(*args, **kwargs)

    return _wrapped

Then apply the decorator to your view function/method:

@view_incrememter
@cache_page(timeout=60)
def show_board(request, pk):
    ...

Or you can use it directly in your urls.py

url(r'^some-path/(?P<pk>\d+)/$', view_incrementer(cache_page(60)(show_board))),
like image 161
Derek Kwok Avatar answered Jun 12 '26 04:06

Derek Kwok