def update_hit_count_ajax(request):
    '''
    Ajax call that can be used to update a hit count.

    Ajax is not the only way to do this, but probably will cut down on 
    bots and spiders.

    See template tags for how to implement.
    '''

    # make sure this is an ajax request
    if not is_cached_hitcount_enabled() or not using_memcache() or not request.is_ajax():
        raise Http404()

    if request.method == "GET":
        return json_error_response("Hits counted via POST only.")

    object_pk = request.POST.get('object_pk', None)
    ctype_pk = request.POST.get('ctype_pk', None)
    
    status = "no hit recorded"
    if object_pk and ctype_pk:
        result = _update_hit_count(request, object_pk, ctype_pk)

        if result:
            status = "success"

    result_dict = {'status': status}
    if CACHED_HITCOUNT_SERVER_CALLBACKS:
        result_dict.update(call_custom_callbacks(request, object_pk=object_pk, ctype_pk =ctype_pk))

    return HttpResponse(json.dumps(result_dict),mimetype="application/json")
def persist_hits():
    if is_cached_hitcount_enabled() and using_memcache():

        backend, location, params = parse_backend_conf(CACHED_HITCOUNT_CACHE)
        host, port = location.split(':')
        hitcount_cache = get_hitcount_cache()
        lock = hitcount_cache.get(CACHED_HITCOUNT_LOCK_KEY)
        #print  'persist_hits - check %s lock = %s' % (CACHED_HITCOUNT_LOCK_KEY, lock)
        if lock is None or lock != 1:
            try:
                #acquire a lock so no updates will occur while we are persisting the hits to DB
                hitcount_cache.set(CACHED_HITCOUNT_LOCK_KEY, 1,
                                   CACHED_HITCOUNT_CACHE_TIMEOUT)
                #print  'acquire %s lock = %s ' % (CACHED_HITCOUNT_LOCK_KEY, hitcount_cache.get(CACHED_HITCOUNT_LOCK_KEY))
                mem = MemcachedStats(host, port)
                keys = mem.keys()

                content_types = {
                }  #used for keeping track of the content types so DB doesn't have to be queried each time
                for cache_key in keys:
                    if "hitcount__" in cache_key and not CACHED_HITCOUNT_IP_CACHE in cache_key:
                        cache_key = cache_key.split(
                            ':'
                        )[-1]  #the key is a combination of key_prefix, version and key all separated by : - all we need is the key
                        count = hitcount_cache.get(cache_key)
                        if count:  #only update the hit count if the is not None
                            hitcount, ctype_pk, object_pk = cache_key.split(
                                '__')
                            if ctype_pk in content_types.keys():
                                content_type = content_types[ctype_pk]
                            else:
                                content_type = ContentType.objects.get(
                                    id=ctype_pk)
                                content_types[ctype_pk] = content_type

                            with transaction_atomic():
                                #save a new hit or increment this hits on an existing hit
                                hit, created = Hit.objects.select_for_update(
                                ).get_or_create(added=datetime.utcnow().date(),
                                                object_pk=object_pk,
                                                content_type=content_type)
                                if hit and created:
                                    hit.hits = long(count)
                                    hit.save()
                                elif hit:
                                    hit.hits = hit.hits + long(count)
                                    hit.save()

                        #reset the hitcount for this object to 0 - even if it was previously None
                        hitcount_cache.set(cache_key, 0,
                                           CACHED_HITCOUNT_CACHE_TIMEOUT)
                        #print  'reset key %s to zero = %s ' % (cache_key, hitcount_cache.get(cache_key))
            except Exception, ex:
                logger.error('Unable to persist hits')
                logger.error(ex)

                raise ex
            finally:
Example #3
0
def persist_hits():
    if is_cached_hitcount_enabled() and using_memcache():

        backend, location, params = parse_backend_conf(CACHED_HITCOUNT_CACHE)
        host, port = location.split(':')
        hitcount_cache = get_hitcount_cache()
        lock = hitcount_cache.get(CACHED_HITCOUNT_LOCK_KEY)
        #print  'persist_hits - check %s lock = %s' % (CACHED_HITCOUNT_LOCK_KEY, lock)
        if lock is None or lock != 1:
            try:
                #acquire a lock so no updates will occur while we are persisting the hits to DB
                hitcount_cache.set(CACHED_HITCOUNT_LOCK_KEY, 1, CACHED_HITCOUNT_CACHE_TIMEOUT)
                #print  'acquire %s lock = %s ' % (CACHED_HITCOUNT_LOCK_KEY, hitcount_cache.get(CACHED_HITCOUNT_LOCK_KEY))
                mem = MemcachedStats(host, port)
                keys = mem.keys()

                content_types = {}#used for keeping track of the content types so DB doesn't have to be queried each time
                for cache_key in keys:
                    if "hitcount__" in cache_key and not CACHED_HITCOUNT_IP_CACHE in cache_key:
                        cache_key = cache_key.split(':')[-1]#the key is a combination of key_prefix, version and key all separated by : - all we need is the key
                        count = hitcount_cache.get(cache_key)
                        if count:#only update the hit count if the is not None
                            hitcount, ctype_pk, object_pk  = cache_key.split('__')
                            if ctype_pk in content_types.keys():
                                content_type = content_types[ctype_pk]
                            else:
                                content_type = ContentType.objects.get(id=ctype_pk)
                                content_types[ctype_pk] = content_type

                            with transaction_atomic():
                                #save a new hit or increment this hits on an existing hit
                                hit, created = Hit.objects.select_for_update().get_or_create(added=datetime.utcnow().date(), object_pk=object_pk, content_type=content_type)
                                if hit and created:
                                    hit.hits = long(count)
                                    hit.save()
                                elif hit:
                                    hit.hits = hit.hits + long(count)
                                    hit.save()

                        #reset the hitcount for this object to 0 - even if it was previously None
                        hitcount_cache.set(cache_key, 0, CACHED_HITCOUNT_CACHE_TIMEOUT)
                        #print  'reset key %s to zero = %s ' % (cache_key, hitcount_cache.get(cache_key))
            except Exception, ex:
                logger.error('Unable to persist hits')
                logger.error(ex)

                raise ex
            finally:
Example #4
0
def update_hit_count_ajax(request):
    '''
    Ajax call that can be used to update a hit count.

    Ajax is not the only way to do this, but probably will cut down on 
    bots and spiders.

    See template tags for how to implement.
    '''

    # make sure this is an ajax request
    if not is_cached_hitcount_enabled() or not using_memcache(
    ) or not request.is_ajax():
        raise Http404()

    if request.method == "GET":
        return json_error_response("Hits counted via POST only.")

    object_pk = request.POST.get('object_pk', None)
    ctype_pk = request.POST.get('ctype_pk', None)

    status = "no hit recorded"
    if object_pk and ctype_pk:
        result = _update_hit_count(request, object_pk, ctype_pk)

        if result:
            status = "success"

    result_dict = {'status': status}
    if CACHED_HITCOUNT_SERVER_CALLBACKS:
        result_dict.update(
            call_custom_callbacks(request,
                                  object_pk=object_pk,
                                  ctype_pk=ctype_pk))

    return HttpResponse(json.dumps(result_dict),
                        content_type="application/json")
 def test_enabled(self):
     self.assertTrue(
         is_cached_hitcount_enabled(),
         msg="Django Cached Hitcount is not enabled (gargoyle switch)")
Example #6
0
 def test_enabled(self):
     self.assertTrue(is_cached_hitcount_enabled(), msg="Django Cached Hitcount is not enabled (gargoyle switch)")