views:

66

answers:

1

I've created the model for counting the number of views of my page:

class RequestCounter(models.Model):
    count = models.IntegerField(default=0)
    def __unicode__(self):
        return str(self.count)

For incrementing the counter I use:

def inc_counter():
    counter = RequestCounter.objects.get_or_create(id =1)[0]
    counter.count = F('count') + 1
    counter.save()

Then I show the number of the page views on my page and it works fine. But now I need to cache my counter for some time. I use:

def get_view_count():
    view_count = cache.get('v_count')
    if view_count==None:
        cache.set('v_count',RequestCounter.objects.filter(id = 1)[0],15)
    view_count = cache.get('v_count')
    return view_count

After this I'm passing the result of get_view_count to my template.

So I expect, that my counter would now stand still for 15 sec and then change to a new value. But, actually, it isn't quite so: when I'm testing this from my virtual ubuntu it jumps, for example, from 55 to 56, after 15 secs it changes and now jumps from 87 to 88. The values are always alternating and they don't differ much from each other. If I'm trying this locally from windows, the counter seems to be fine, until I try to open more than browser. Got no idea what to do with it. Do you see what can be the problem?


p.s. i tried using caching in the templates - and received the same result.

+3  A: 

What CACHE_BACKEND are you using? If it's locmem:// and you're running Apache, you'll have a different cache active for each Apache child, which would explain the differing results. I had this a while ago and it was a subtle one to work out. I'd recommend switching to memcache if you're not already on it, as this won't give you the multiple-caches problem

stevejalim
Right you are, i'm using locmem:// and i'm on Apache..Does it mean, that if I'll switch to memcache or change CACHE_BACKEND my code will work fine?
loder
You'll have to change your CACHE_BACKEND to memcache (see the Django cache docs) in order to be able to use memcached. (As well as potentially setting up memecached, but that's pretty straightforward with apt-get). Because memcached is shared by all Apache threads/children, there will only be one set of cached data for your app, your problem will probably stop -- assuming I'm right in thinking that the multiple-locmem cacheing is what's at the root of it :o)
stevejalim
Yes, thanks, that solved the problem! It was enough to change lockmem=)
loder